IBM Metal C

Examples

Example 11. Pseudorandom Number Generator (PRNG)

This example is a pseudorandom number generator based on the Mersenne Twister, a uniform pseudorandom number generating algorithm developped by Makoto Matsumoto (松本 眞) and Takuji Nishimura (西村 拓士). The algorithm has a period of 219937-1 and according to Wikipedia, is the most widely used PRNG.

The implmentation presented here, MT19937, is based upon the Mersenne prime value of 19937 (a Mersenne prime has a value of 2n-1). This version uses a 32 bit word.

Some of the features of the Mersenne Twister PRNG are that it is fast, has a very long period, and passes numerous tests for statistical randomness. To test the speed of this implementation, I ran multiple tests, generating n 31-bit numbers. N ranged from 1,000 to 2 billion. The results are shown in the table and graph below.

MT Random Number Generation - 31 bit Numbers
CPU Time (s)
No.
Numbers
Generated
CPU sec/
/Number
μs
/Number
0.01 1,000 0.000010000 10.00
0.02 25,000 0.000000800 0.80
0.02 50,000 0.000000400 0.40
0.02 75,000 0.000000267 0.27
0.02 100,000 0.000000200 0.20
0.03 250,000 0.000000120 0.12
0.07 750,000 0.000000093 0.09
0.09 1,000,000 0.000000090 0.09
0.75 10,000,000 0.000000075 0.08
7.43 100,000,000 0.000000074 0.07
18.49 250,000,000 0.000000074 0.07
74.05 1,000,000,000 0.000000074 0.07
148.11 2,000,000,000 0.000000074 0.07

Testing shows that there is some "startup" overhead for this implementation. Between 1,000 and 250,000 generated numbers, the CPU time was between 0.01 and 0.02 seconds. After that the CPU time starts to grow in a more linear fashion. Note that the CPU time is that recorded from the job log output and not from SMF records, so there is a limitation to the accuracy of the recorded values. For small values of n, each generated number took about 10 microseconds. For larger values of n, the number drops to 0.07 microseconds or 70 nanoseconds.

Chart of Generated Numbers versus CPU Time

Test Statistics

Some simple statistics on the 1 million generated numbers are:

Sample Statistics
Statistic Value
Mean 1,073,012,722
Median 1,073,240,357
Skewness 0.000737755
Range 2,147,481,371
Minimum 1,993
Maximum 2,147,483,364
Count 1,000,000

The MT generator prooduces a uniform distribution of random numbers. To test that claim, I produced a histogram of the 1 million numbers generated by the test. The chart below shows the distribution of the generated numbers. Visually, the sequence appears uniform.

C Source Code

References

  1. Mersenne Twister Home Page
  2. Mersenne twister - Wikipedia Entry
  3. National Institute of Standards and Technology (NIST). Random Number Generation