Main Menu

Pushing the Limits in Java's Random

Welcome to the 198th issue of The Java(tm) Specialists' Newsletter sent to you from Chania in Greece. My readers in colder climates frequently get annoyed when I tell them that "life's a beach". They imagine us having constant sun here. It's not true. We do sometimes have torrential rains and cold weather. It even snows here occasionally. In fact, the delivery truck for my heating oil arrived as I was writing this.

Pushing the Limits in Java's Random

My previous newsletter caused quite a stir. I saw lots of wrong answers and some excellent explanations. Quite a few thought that Math.random() did indeed sometimes return 1.0. It does not, but the value is sometimes close enough to 1.0 that we lose precision in the rounding.

Here is what the nextDouble() calculation looks like in java.util.Random:

One of our most thorough readers, Dr. Wolfgang Laun, went on a voyage of discovery to find out what the highest number was that could possibly be returned by Math.random(). This newsletter is a summary of his findings, plus some other tidbits that I discovered. Dr. Laun lives in Vienna in Austria and works for Thales as their local software guru. I've had the pleasure of meeting him personally and been invited for dinner at his house. He is probably the most intelligent human being I have met. And he also has a great sense of humour and a keen curiosity of how the world works. I am honoured to count him as a friend.

The first question that Wolfgang tried to answer is: Can (int)(Math.random() + 1) ever return 2? I thought it could. The calculation for producing the double is to make up a 53 bit number and to then divide it by 2^53. This means that the maximum possible number would be ((2^53)-1)/(2^53), or 0.9999999999999999. You can calculate this easily:

System.out.println((((1L << 53) - 1)) / (double) (1L << 53));

If we use the standard Random calculation as shown in makeDouble(), if we add 1 and cast it to an int, the result will be 2. For example:

In our previous newsletter, "meaning" was sometimes incremented by two, when Math.random was close enough to 1 and "meaning" was large enough. For example, if "meaning" is 100_000_000, we don't need to be as close to 1 as if "meaning" is 1.

The point to note is that it is based on a 48-bit seed. In order for (int)(Math.random() + 1) to be 2, all the bits would have to be set on the left. If it is just one less, then the double would equal 0.9999999999999998 and this would not round up to 2.

Since the next random value is based on the current value, all we would need to check is whether there exists a 48-bit number with the lower 26 bits set, such that the next number has the lower 27 bits set. If we find such a number, then we can conclude that at least in theory, it is possible for Math.random() to return 0.9999999999999999. We would still need to establish for what random seed we could get this number. If we did not find such a number, then we could conclude that it was not possible.

Wolfgang wrote the code to calculate the largest number that could be returned by Math.random():

From this, we can calculate that the highest number that can be returned by Math.random() is 0.999999999999996, whereas the highest double less than 1.0 is 0.9999999999999999, a difference of .0000000000000039.

Concurrency

We could stop here, were it not for concurrency. However, the Math.random() method delegates to a shared mutable instance of Random. Since they use atomics, rather than locking, it is impossible for the compound nextDouble() method to be atomic. Thus it is possible that in between the two calls to next(27) and next(26), other threads call next(). Remember the code for Random.nextDouble() from earlier:

In theory, if you had thousands of threads calling Math.random() at the same time, your thread could be swapped out for long enough, so that (int)(Math.random() + 1) could return 2. The probability of this happening might be greater than zero, but it is infinitesimally small. For example, in my experiments I did find a value of next(26) for which, if it was swapped out long enough and other threads had called next(27) 105 times, next(27) would return a number with all bits set. As Wolfgang told me, I'm rapidly entering into the realms of the metaphysical here.

Java 7 ThreadLocalRandom

As of Java 7, we should never again use Math.random(). Java 7 gives us a new ThreadLocalRandom class that has one unshared Random instance per thread. Since it is an unshared object, they do not need to have any synchronization to prevent data races. As a result it is blazingly fast.

We can use it like this: ThreadLocalRandom.current().nextInt(3000);

In this example, we construct 20 buttons and let them change color at a random interval using ThreadLocalRandom. I will go over this code again in another newsletter, as it also demonstrates the new Java 7 Phaser class.

If you run the Blinker with a version of Java 7 older than 1.7.0_02, you will notice that all the colors and delays are always the same. This is due to a bug in the constructor of java.util.Random, which failed to set the seed correctly on the subclass. Time to upgrade to the latest version of Java 7. Note that if you are using Mac OS X Snow Leopard or Leopard, the Mac OS X Port installer will tell you that you need to upgrade to Lion. Instead, I used Pacifist to extract the DMG file. I am not ready to install Lion on my work machines yet.

(int)(Math.random() * some_int)

A common code idiom is to multiply the result of Math.random() with some integer value. There are several reasons not to do that anymore. First off, Math.random() is using a shared mutable instance of Random, thus it needs to be synchronized. It does use atomics to eliminate locking, but with lots of threads calling Math.random(), you might still need to redo your work several times until you emerge as the winner.

The second reason is that Math.random() calls nextDouble(), which as we have seen, will call next(bits) twice.

The third reason is that nextDouble() * int is more biased. We will get a fairer distribution if we call nextInt(upto).

One Last Thing

Concurrency allows us to do some strange things. For example, we can set the seed on a shared mutable Random instance so that eventually, (int)(random.nextDouble() + 1) will return 2. Here is the code: