Program 9.1: Test The Randomness of a Random Number Generator

As the second example consider a class which counts the occurrences of the digits 0-9. For example you might wish to test the randomness of a random number generator. If a random number generator is truly random, all digits should occur with equal frequency over a sufficiently long period of time.

You will do this by creating an array of ten longs called ndigit. The zeroth component of ndigit will track the number of zeros; the first component will track the numbers of ones and so forth. Program 9.1 tests Java's random number generator to see if it produces apparently random numbers.

Below is one possible output from this program. If you run it your results should be slightly different. After all this is supposed to be random. These results are pretty much what you would expect from a reasonably random generator. If you have a fast CPU and some time to spare, try bringing the number of tests up to a billion or so, and see if the counts for the different digits get any closer to each other.