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 = seedRand(1337);
int i;
for(i=0; i<1000; i++) {
printf("%f\n", genRand(&r));
}
return 0;
}
Public domain. Have fun!