I need to generate a random number that is between a minimum value and 1 -> [min, 1)
I have been reading over the random class of java, and have found that when generating a random double, the result is a double from 0 to 1.0, however, you cannot limit the bound.
My original thought was to limit the top value of the random function to .7, but this is not possible with the random function.
If anyone could help me here’s my code:
public static double random(){
// generate an random number accuracy within range [min, 1)
Random randomNum = new Random();
double accuracy = min + randomNum.nextDouble();
System.out.println("Min " + min);
return accuracy;
}
If for example we take min to be .2 in this case, then the possible results of the function as I understand are .2 to 1.2. How can I make it simply .2 to 1?
Correct me if I’m wrong, but wouldn’t this work:
Explanation:
(max - min)returns the difference betweenmaxandmin.randomNum.nextDouble()returns a random number between0and1+ minwill add theminvalue so it’s the lowest value(max - min) * randomNum.nextDouble()returns a random number between0andmax-min(max - min) * randomNum.nextDouble() + minreturns a random number betweenminandmax