Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Random.nextDouble() ever return the inclusive value?

Tags:

java

random

I was playing around with the Random class's nextDouble() method as shown below. I expected nextDouble() to return a pseudorandom double value on the interval [-50.0, 50.0), however, after running the loop 1 billion times the output came out to maximum: 49.99999995014588 minimum: -49.99999991024878. I ran the loop without my manipulations of the output interval, and I got maximum: 0.9999999998979311 minimum: 0.0. I find this strange, because all I have done to the 0.0 that was returned is multiply it by 100.0 and subtract 50.0 from it. Why does this code snippet below never return exactly -50.0?

EDIT: Just for fun I ran the loop another 500 million times, and the output is now: maximum: 49.99999994222232 minimum: -49.999999996750944.

import java.util.Random;

public class randomTest{

public static void main(String[] args) {

    double max = 0;
    double min = 0;
    Random math = new Random();
    for(int a = 0; a < 1000000000; a++) {
        double rand = math.nextDouble() * 100.0 - (100.0 / 2.0);
        max = Math.max(max, rand);
        min = Math.min(min, rand);
    }
    System.out.println("maximum: " + max + " minimum: " + min);
}
}
like image 996
Ungeheuer Avatar asked Dec 05 '22 16:12

Ungeheuer


1 Answers

The javadoc clearly states that the upper bound on nextDouble() is exclusive not inclusive. That means that 1.0 will not be returned.

According to the javadoc, 0.0 will be returned .... with a probability of approximately 1 in 254. (That is one time in 18,014,398,509,481,984.)

(It boils down to determining whether two successive calls to next(27) will return zero. That is possible, if you examine the specification for the LCNG used by next(int).)


So, your code doesn't hit 50.0 because it can't. It should be able to hit -50.0 but you would probably need to run it in the order of 1.0E19 times for that to happen. You only ran it 5.0E8 times.

like image 125
Stephen C Avatar answered Dec 08 '22 05:12

Stephen C