A Java Programmer's Guide to Random Numbers, Part 1: Beyond java.util.Random
Join the DZone community and get the full member experience.Join For Free
this is the first in a series of articles about random numbers in java programs. the series covers the following topics and also serves as an introduction to the random numbers package of the uncommons maths library.
- true random numbers and pseudorandom numbers
- statistical quality (making sure the dice are not loaded)
- performance (because sometimes you really do need half a million random numbers a second)
- different kinds of randomness (because not everything can be modelled by tossing a coin)
- degrees of freedom (is every possible outcome actually possible?)
- security and integrity (when not losing money depends on nobody knowing what happens next)
random numbers are useful in a wide variety of software applications. they provide a crucial element of uncertainty in an otherwise deterministic world. without random numbers in computers, the hugely popular online poker industry would not exist, video games would be boring and predictable, itunes would have no shuffle, cryptography would be much more difficult, and many innovative algorithms, such as those used in artificial intelligence and evolutionary computation, simply couldn’t work.
true random numbers and pseudorandom number
“anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin.” - john von neumann
before continuing, it is important to make the distinction between so-called “true” random numbers and pseudorandom numbers. though it may often seem otherwise to us as programmers, computer systems are infuriatingly deterministic. they are generally incapable of doing things randomly. to get a computer to behave in a way that is truly random, it is necessary to introduce some non-deterministic input. we could have somebody constantly rolling dice or flipping coins and typing in the results, but that is not very practical. a slightly more feasible approach is to construct a device that observes some real world phenomenon that is known to be unpredictable, such as radioactive decay or atmospheric noise. data extracted from these events can be used a source of entropy for our applications. you could purchase a device that plugs into a serial port or usb port. to access these devices from java you’d probably have to use c/c++ and jni. alternatively, you could get true random numbers indirectly - from an online service such as random.org or hotbits .
since we can get truly unpredictable random numbers from this kind of hardware, why don’t we satisfy all of our randomness requirements in this way? well the primary problem is throughput. these devices are quite limited in the quantity of randomness they can produce. they simply aren’t fast enough for many uses.
pseudorandom numbers are not really random at all. they are the result of deterministic mathematical formulae. the best of these algorithms have been devised so that their output is statistically indistinguishable from true random numbers. prngs start with a single numeric seed value. the algorithm is applied to this seed to generate the output and a new, updated seed that is used to generate the next value. the mathematics involved is beyond the scope of this article - the definitive guide is the second volume of donald knuth’s the art of computer programming.
an interesting property of this approach is that if you always start with the same seed value, you will always get the same sequence of “random” numbers. though this can occasionally be useful, you would normally strive to avoid using the same seed value in the interests of unpredictability. a simple approach that is sufficient in many cases is to seed the prng from the current value of the system clock.
aside from speed, another advantage of pseudorandom number generators (prngs) over true random number generators (trngs) is that they are more predictably unpredictable. that is, the statistical properties of prngs are more reliable than is the case with trngs.
why not java.util.random?
the java api helpfully provides a prng that we can use, the java.util.random class. if you are a java programmer you will almost certainly have used it at some point. for non-critical random numbers, e.g. adding some unpredictability to a game, it’s fine. it’s even pretty quick. unfortunately, it’s not random enough - not by the standards required for more serious applications.
the problem of deciding whether a sequence of numbers is random is not an easy one to solve. you can’t simply look at the output and decide that it doesn’t look random enough. after all, if you toss a coin ten times, it could randomly come up heads every time, even though the probability of this sequence is pretty small. to get any kind of meaningful evaluation requires a large sample of the rng output (perhaps millions of generated values). this sample can then be subjected to sophisticated statistical analysis.
probably the best known test suite for random number generators is george marsaglia’s diehard battery of tests of randomness . diehard says that java.util.random is not sufficiently random. but you don’t have to interpret diehard’s complicated reports to see for yourself. this applet demonstrates it visibly.
so if not java.util.random, how about java’s other rng, java.security.securerandom ? securerandom is built for cryptography so it is specifically designed to avoid any such flaws. diehard reports no issues with its output. unfortunately, this quality comes at a high price - performance. in benchmarks, securerandom can be up to 60 times slower at generting random numbers than java.util.random. this is bearable if you are only generating random values infrequently, but if your program relies on generating random numbers non-stop and as fast as possible (as many simulations do) then it’s a show-stopping bottleneck.
the good news is that, beyond the core api, there are random number generators as fast as, or faster than, java.util.random with statistical properties as good as securerandom. the uncommons maths project provides a comprehensive open source random numbers package . uncommons maths provides three random number generators, with different properties, for a wide variety of applications. unlike java.util.random, each of these rngs completes the diehard suite without any problems. additionally, each of the uncommons maths rngs is a sub-class of java.util.random, which means any of them can be used as a drop-in replacement with minimal effort.
a good general-purpose prng is the mersennetwisterrng class. it is a pure java port of makoto matsumoto and takuji nishimura’s proven and ultra-fast mersenne twister prng for c. even faster is cellularautomatonrng , the java port of tony pasqualoni’s experimental cellular automaton prng .
Opinions expressed by DZone contributors are their own.