The Mersenne twister is a pseudo-random number generation algorithm that was developed in 1997 by Makoto Matsumoto (松本 眞) and Takuji Nishimura (西村 拓 士). Although improvements on the original algorithm have since been made, the original algorithm is still both faster and "more random" than the built-in generators in many common programming languages (C and Java included).
There are already many implementations of the algorithm, so why did I write one myself? There are a number of reasons:
- the pseudocode on Wikipedia suggested that it was relatively simple to implement;
- I never trust pseudocode on Wikipedia, so I wanted an implementation from the original academic paper; and
- it would have been just as easy to implement it myself than to figure out the API of someone else's ugly C code.
Note that this code has not been tested to a sufficient extent to be confidently used for cryptography.
The following code will create a new random generator seeded at 1337
and print out one thousand random doubles between 0 and 1.
#include <stdio.h>
#include "mtwister.h"
int main() {
MTRand r = MT_SeedRand(1337);
for(int i=0; i < 1000; i++) {
printf("%f\n", MT_GenRand_F64(&r));
}
}
Public domain. Have fun!