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)?
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With