I know you can use Math.random() in Java to generate a random double from 0.0 to 1.0, but how does the computer pick a number? What code is the computer following to simulate randomness?
解决方案
That's easily found by looking at the docs since, happily, the behavior is well-defined in Java. From Math, it says
When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression
new java.util.Random()
Sadly it doesn't explicitly say which method on Random it calls. However, since its return value is in the same range as Random.nextDouble, which it also links to in the "See Also" section, it should be a safe assumption that that is what is used.
return (((long)next(26) << 27) + next(27))
/ (double)(1L << 53);
atomically updating the seed to
(seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)
and returning
(int)(seed >>> (48 - bits))
So the final random value is calculated as
seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)
next1 = (int)(seed >>> (48 - 26))
seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)
next2 = (int)(seed >>> (48 - 27))
randomValue = (((long)next1 << 27) + next2) / (double)(1L << 53);
Where
the seed of the random number generator [is initialized as] a value very likely to be distinct from any other invocation of this constructor.
By looking at this, it should be pretty clear that the number is not, in fact, "random" as most people would understand it. It's a completely predictable mathematical pattern, known as pseudorandom, which is random enough for many purposes. However, it might be worth looking into SecureRandom (which produces unpredictable, cryptographically strong random values), depending on how unpredictable you want the results to be.