richbai90 - 6 months ago 25

Java Question

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

`nextDouble`

`[0.0,1.0)`

`(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.