Just out of curiosity, can Math.random() ever be zero?
For example, if I were to have:
while (true){
if (Math.random() == 0)
return 1;
}
Would I ever actually get a return of one? There's also rounding error to consider because Math.random() returns a double.
I ask because my CS professor stated that random() goes from 0 to 1 inclusive, and I always thought it was exclusive.
nextInt(int n) : The nextInt(int n) is used to get a random number between 0(inclusive) and the number passed in this argument(n), exclusive.
The Matlab function rand() excludes zero. It is using the range (0, 1). In Python/Numpy the functions random. random() is using the range [0.0, 1.0).
Math. random() can never generate 0 because it starts with a non-zero seed. Set the seed to zero, the function does not work, or throws an error. A random number generator always returns a value between 0 and 1, but never equal to one or the other.
random() Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
Yes, it really can be. Math.random()
creates a global java.util.Random
-generator with seed (System.currentTimeMillis() ^ 0x5DEECE66DL) & ((1L << 48) - 1)
and calls nextDouble()
for it. If its seed reaches state 107048004364969L
(and it will, since java.util.Random
has full period), the next double
generated will be 0.0
.
Though with bad luck you could end up with the wrong parity in the cycle, because
Random.nextDouble()
advances the state twice. With little less bad luck you could have to generate 2^47 random numbers before the loop terminates, as I didn't find any other seeds that give 0.0
.
The seed advances as if by seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
and doubles are generated using 26 and 27 upper bits of two consecutive seed values. In the example the two next seed values will be 0L
and 11L
.
If you manage to create the global generator with System.currentTimeMillis()==107038380838084L
, your code returns immediately. You can simulate this with:
java.util.Random k = new java.util.Random(107038380838084L);
System.out.println(k.nextDouble()==0);
According to the documentation, "Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0." This means it can be zero.
As Hank wrote, it is exclusive on the upper boundary (can never be 1), so maybe that's where your confusion comes from :-).
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