Mersenne Twister (MT) produces pseudorandom number with much longer period (2^19937-1) than the most widely used one-dimension linear congruential generator (LCG; typically below 2^64-1), which is used by rand() and rand48() in libc. Of equal importance, MT approaches the speed of LCG. It is about 40% slower on my Mac laptop than lrand48() and faster than lrand48() on a Linux machine. The boost developers have also benchmarked various pseudorandom number generators. Their conclusion is broadly similar to mine. In all, MT is a far better pseudorandom generator.
Takuji Nishimura and Makoto Matsumoto, the father of MT, have implemented the algorithm in C for both 32-bit and 64-bit integers. Many others have adapted or improved it. I also wrote a wrapper in klib. To use it:
#include "krand.h" krand_t *kr = kr_seed((uint64_t)time()<<32^getpid()); uint64_t x = kr_rand(kr); free(kr);
In the context of multi-threading, each thread should call kr_seed() with a different seed. You can also call kr_seed() once, but kr_rand() needs to be locked.
It would be interesting to compare also marsaglia KISS random generator
that has a period of 2^123, it’s simpler than mersenne twister, and has
very good statistical properties (no flaws in L’Ecuyer big crush tests).
Have a look at https://bitbucket.org/cmcqueen1975/simplerandom/wiki/Home
for a clean and simple implementation.
PS: thanks for klib!
PPS: I’m waiting for your review of mozilla’s rust language
It seems to me that KISS may be a little slower than Mersenne Twister due to the slower integer math. I will test it later. Thanks a lot.
Probably I am not the best guy to review rust. I indeed tried to compile it, but unfortunately failed.
It is great yo hear you like klib. I am satisfied as a half-programmer. Thanks.