I am not very familiar with how to alter the range of both Math.random or a new Random() to generate a double like this. I need to be able to generate a double between -10 and 25 cents (my program is dealing with money; hence why I said cents). And a separate instance is generating a random double between 90 and -75 cents. I saw this when I was searching for my answer:
double result = Math.random() * (upper - lower) + lower;
But when I implemented the idea into my code, the range didn't seem to work when using a range between a positive and a negative number...
I tested it with the upper limit of 0.25 and lower of -0.10, but noticed it printed 0.3567587946356543 at one instance of the test I did. So by this I concluded that I obviously didn't adjust the range correctly..
Please help :(
This is my first time using stackoverflow so please go easy on me, I will elaborate if anything I said didn't make sense..
This is my existing method using this code:
public double variation(double price){
//formula: (Math.random() * range) + min; where range = max - min
//80% of the time returns amount between -10 & 25 cents
if(Math.random() > 0.19){
return (Math.random() * 0.35) - 0.10;
}
//20% of the time returns amount between -75 & 90 cents
return (Math.random() * 1.65) - 0.75;
}
I know the method takes in a double price that it doesn't use; it's part of the teacher's requirements to take in a double price but to disregard its value. So ignore that please.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…