Here's the idea. You want a random number in a range, let's say [-1.1,2.2]
, to start with a simple example. That range has length 3.3 since 2.2 - (-1.1) = 3.3
. Now most "random" functions return a number in the range [0,1)
, which has length one, so we have to scale our random number into our desired range.
Random random = new Random();
double rand = random.nextDouble();
double scaled = rand * 3.3;
Now our random number has the magnitude we want but we must shift it in the number line to be between the exact values we want. For this step, we just need to add the lower bound of the entire range to our scaled random number and we're done!
double shifted = scaled + (-1.1);
So now we can put these parts together in a single function:
protected static Random random = new Random();
public static double randomInRange(double min, double max) {
double range = max - min;
double scaled = random.nextDouble() * range;
double shifted = scaled + min;
return shifted; // == (rand.nextDouble() * (max-min)) + min;
}
Of course, this function needs some error checking for unexpected values like NaN
but this answer should illustrate the general idea.