MSDN Archive Home
Help and FAQs
Better random numbers in .Net: an updated Mersenne Twister in C#
All Resource Updates
Change History (all pages)
The Mersenne Twister is a rather well-known algorithm for generating pseudo-random numbers. It is fast and has a huge period (range over which it doesn't repeat itself), which makes it ideal for simulation. However, the sequence can be guessed after only 624 numbers have been generated, so it is not useful for cryptography. It was first published in 1998 by Makoto Matsumoto and Takuji Nishimura using C code. *
An acquaintance of mine, Trevor Misfeldt, converted the C code to C# and published it to
. Another implementation in C# is from Akihilo Kramot at
I've taken both of these and created this version, since Trevor's is a fairly straight conversion from the C-code, yet has some compelling methods, and Akihilo Kramot's implementation is clean and well-adapted to .Net (implements System.Random), but contains a small bug in the NextBytes method.
I have also implemented the 53-bit variety of the algorithm for the NextDouble* methods after an
was published in the journal
Monte Carlo Methods and Applications
, Vol. 12, No. 5-6, pp. 385 – 393 (2006), entitled "A Repetition Test for Pseudo-Random Number Generators" highlighting that, somewhat unsurprisingly, the 32-bit variety for double floating points makes numbers repeat too soon in a sequence, whereas the 53-bit variety does not.
This code is currently being used in the
library to provide random numbers for the numerical algorithms there. That project also has rudimentary unit tests covering this code for sanity checking (testing correct parameter guarding, primarily). I also hope to add at least one randomness test in order to verify the implementation (the algorithm has already tested).
For the interested, more information on the Mersenne Twister can be found on
and appears, as of this posting, fairly accurate and useful. This could, however, change at any moment.
* Published in the ACM's Transactions on Modeling and Computer Simulation Vol. 8, No. 1, January pp.3-30 (1998).
Feb 27 2008 at 1:24 AM
, version 6
Sign in to add a comment
Tue Feb 26 2008 at 8:00 AM
More Tags ...
Visual Studio 2005
Visual Studio 2008
Visual Studio 2010
Manage Your Profile
MSDN Flash Newsletter
© 2008 Microsoft Corporation. All rights reserved.