I want to use math.random() in a Java program.
What is the distribution of this way of getting doubles?
Advertisement
Answer
This is documented in the Java SE API docs:
public static double random()
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.
The doc goes on to mention that it uses java.util.Random
under the hood, presumably nextDouble() (although not explicitly stated).
The remarks about nonuniformity in nextDouble are as follows:
The method nextDouble is implemented by class Random as if by:
public double nextDouble() { return (((long)next(26) << 27) + next(27)) / (double)(1L << 53); }The hedge “approximately” is used in the foregoing description only because the next method is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm shown would choose double values from the stated range with perfect uniformity.
It appears that the non-uniformity is only due to the underlying nonuniformity of next
rather than a significant bias in the nextDouble algorithm itself:
[In early versions of Java, the result was incorrectly calculated as:
return (((long)next(27) << 27) + next(27)) / (double)(1L << 54);This might seem to be equivalent, if not better, but in fact it introduced a large nonuniformity because of the bias in the rounding of floating-point numbers: it was three times as likely that the low-order bit of the significand would be 0 than that it would be 1! This nonuniformity probably doesn’t matter much in practice, but we strive for perfection.]
Note that this draws uniformly from the interval [0,1] separated into equal steps of 2-53, which is not the same as drawing uniformly from the set of all double
values whose values are between 0 and 1. This is a subtle difference: the set of all double
values between 0 and 1 is itself not uniformly spaced on the number line as this image shows:
image reproduced from docs.oracle.com