Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 777
richbai90 Avatar asked Nov 28 '25 01:11

richbai90


2 Answers

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.

like image 78
Andreas Avatar answered Nov 29 '25 14:11

Andreas


Rather than asking for the minimum exclusively, you could ask for it inclusively -- but have the minimum be the next value of double using Math::nextUp:

min = Math.nextUp(min);

Doubles are discrete, so this is analogous to in integer-land, rephrasing (0, 10) as [1, 10).

like image 41
yshavit Avatar answered Nov 29 '25 13:11

yshavit