This content has been marked as final. Show 9 replies
Math.random() uses Random.nextDouble() internally.
Random.nextDouble() uses Random.next() twice to generate a double that has approximately uniformly distributed bits in its manitissa, so it is uniformly distributed in the range 0 to 1-(2^-52).
Random.nextInt(n) uses Random.next() less than twice on average- it uses it once, and if the value obtained is above the highest multiple of n below MAX_INT it tries again, otherwise is returns the value modulo n (this prevents the values above the highest multiple of n below MAX_INT squewing the distribution), so returning a value which is uniformly distributed in the range 0 to n-1.
Prior to scaling by 6, the output of Math.random() is one of 2^52 possible values drawn from a uniform distribution.
Scaling by 6 doesn't alter the number of possible values, and casting to an int then forces these values into one of six 'buckets' (0, 1, 2, 3, 45), each bucket corresponding to ranges encompassing either 1501199875790165 or 1501199875790166 of the possible values (as 6 is not a disvisor of 2^52). This means that for a sufficient number of dice rolls (or a die with a sufficiently large number of sides), the die will show itself to be biased towards the larger buckets.
You will be waiting a very long time rolling dice for this effect to show up.
Math.random() also requires about twice the processing and is subject to synchronization.
Pete, thank you for your exhaustiveWell, it's a theoretical argument with practical consequences. Using nextInt you get a more uniform distribution of random integers. It's still not "true" randomness but it's the closest you get with a standard API method so why not use it?
In the context of the original question this is of
course a more or less theoretical argument. According
to Ulrica's post I had expected more direct
Well, it's a theoretical argument with practicalAs a general rule, yes. Yet the practical consequences are well below any statistical significance. The bias that was described is one part in 2^53, but the maximum cycle length of the PRNG used is only 2^48.
consequences. Using nextInt you get a more uniform
distribution of random integers. It's still not "true"
randomness but it's the closest you get with a
standard API method so why not use it?
So what you will see in the application is the data distribution of the underlying PRNG, not the bias.