faku
faku

Reputation: 441

How to randomly get a double from a range

I'm actually working an a project and I have a problem : I have to generate a random Double value from range [a, b]. By searching on internet, some people say that the following formula works :

b + (b - a) * random.nextDouble();

But if we do some calculus, we found that it's impossible for a to be included.

How can I do such a thing ? Does anyone have any clue ?

Thanks in advance for the help !

Upvotes: 0

Views: 97

Answers (2)

Alnitak
Alnitak

Reputation: 339786

The nextDouble function works by creating a 53 bit integer, and then dividing it by 2 ^ 53. From the javadocs:

 public double nextDouble() {
      return (((long)next(26) << 27) + next(27))
          / (double)(1L << 53);
 }

This therefore produces the range [0, 1) - the upper bound approaching the limit of (n - 1) / n.

To create the fully inclusive range instead, create that 53 bit integer yourself, but divide instead by (2 ^ 53) - 1.

Note that to all intents and purposes the difference between inclusive and exclusive barely matters - the odds of hitting 1.0 exactly with the modified code is 1 / ((2 ^ 53) - 1) - an almost infinitesimally small number.

Furthermore, this division by (2 ^ 53) - 1 will be potentially a lot slower than the original code. Division by 2 ^ n is utterly trivial for a CPU because all it does is decrement the floating point exponent and potentially left shift the mantissa. That - 1 on the divisor makes the division a lot more long-winded, and may even make the resulting sequence less random than it should in the lower order bits.

Upvotes: 3

Tarek
Tarek

Reputation: 771

This is more logical

 a + (b - a) * random.nextDouble();

Update:

But this logic will exclude b, since random.nextDouble(); ranges between [0,1), which means it doesn't include 1.

Upvotes: 2

Related Questions