richbai90 richbai90 - 2 months ago 11
Java Question

how to get next random double on an open interval (x, y)

I know the basic algorithm for a random number in a half-closed interval is:

Random rand = new Random();
double increment = min + (max - min) * rand.nextDouble();


This will give you a random number on the interval
[min, max)
because
nextDouble
includes 0 in the range of results (
[0.0,1.0)
) that it returns. Is there a good way to exclude the minimum value and instead provide a random number on
(min, max)
?

Answer

In theory, calling Math.nextUp(double d) should do it.

double minUp = Math.nextUp(min);
double increment = minUp + (max - minUp) * rand.nextDouble();

In reality, rounding after multiplication may still cause min to be returned, so a retry loop would be better. Given the rarity of an exact min value, performance won't suffer.

double increment;
do {
    increment = min + (max - min) * rand.nextDouble();
} while (increment <= min || increment >= max);

Just for heck of it, I also added a max check.