Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Java's random function be zero?

Tags:

java

random

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.

like image 846
ThirdD3gree Avatar asked Jun 17 '10 20:06

ThirdD3gree


People also ask

Does random nextInt include 0?

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.

Can rand function generate 0?

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

Can math random generate 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.

Does random in Java include 0?

random() Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.


2 Answers

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

like image 143
Angs Avatar answered Sep 19 '22 03:09

Angs


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 :-).

like image 45
Matt Solnit Avatar answered Sep 17 '22 03:09

Matt Solnit