core/logic/MersenneTwister.h
author Kyle Sanderson <kyle.leet@gmail.com>
Mon Aug 12 00:42:56 2013 +0100 (2013-08-12)
changeset 3994 4bc73bac0f4c
parent 2833 e7e7e77e679d
permissions -rw-r--r--
Added helper stock to check if a command exists. (bug 5510, r=asherkin)
     1 // MersenneTwister.h
     2 // Mersenne Twister random number generator -- a C++ class MTRand
     3 // Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus
     4 // Richard J. Wagner  v1.0  15 May 2003  [email protected]
     5 
     6 // The Mersenne Twister is an algorithm for generating random numbers.  It
     7 // was designed with consideration of the flaws in various other generators.
     8 // The period, 2^19937-1, and the order of equidistribution, 623 dimensions,
     9 // are far greater.  The generator is also fast; it avoids multiplication and
    10 // division, and it benefits from caches and pipelines.  For more information
    11 // see the inventors' web page at http://www.math.keio.ac.jp/~matumoto/emt.html
    12 
    13 // Reference
    14 // M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-Dimensionally
    15 // Equidistributed Uniform Pseudo-Random Number Generator", ACM Transactions on
    16 // Modeling and Computer Simulation, Vol. 8, No. 1, January 1998, pp 3-30.
    17 
    18 // Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
    19 // Copyright (C) 2000 - 2003, Richard J. Wagner
    20 // All rights reserved.                          
    21 //
    22 // Redistribution and use in source and binary forms, with or without
    23 // modification, are permitted provided that the following conditions
    24 // are met:
    25 //
    26 //   1. Redistributions of source code must retain the above copyright
    27 //      notice, this list of conditions and the following disclaimer.
    28 //
    29 //   2. Redistributions in binary form must reproduce the above copyright
    30 //      notice, this list of conditions and the following disclaimer in the
    31 //      documentation and/or other materials provided with the distribution.
    32 //
    33 //   3. The names of its contributors may not be used to endorse or promote 
    34 //      products derived from this software without specific prior written 
    35 //      permission.
    36 //
    37 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    38 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    39 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    40 // A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
    41 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    42 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    43 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    44 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    45 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    46 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    47 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    48 
    49 // The original code included the following notice:
    50 //
    51 //     When you use this, send an email to: [email protected]
    52 //     with an appropriate reference to your work.
    53 //
    54 // It would be nice to CC: [email protected] and [email protected]
    55 // when you write.
    56 
    57 #ifndef MERSENNETWISTER_H
    58 #define MERSENNETWISTER_H
    59 
    60 // Not thread safe (unless auto-initialization is avoided and each thread has
    61 // its own MTRand object)
    62 
    63 #include <limits.h>
    64 #include <stdio.h>
    65 #include <time.h>
    66 #include <math.h>
    67 
    68 class MTRand {
    69 // Data
    70 public:
    71 	typedef unsigned long uint32;  // unsigned integer type, at least 32 bits
    72 	
    73 	enum { N = 624 };       // length of state vector
    74 	enum { SAVE = N + 1 };  // length of array for save()
    75 
    76 protected:
    77 	enum { M = 397 };  // period parameter
    78 	
    79 	uint32 state[N];   // internal state
    80 	uint32 *pNext;     // next value to get from state
    81 	int left;          // number of values left before reload needed
    82 
    83 
    84 //Methods
    85 public:
    86 	MTRand( const uint32& oneSeed );  // initialize with a simple uint32
    87 	MTRand( uint32 *const bigSeed, uint32 const seedLength = N );  // or an array
    88 	MTRand();  // auto-initialize with /dev/urandom or time() and clock()
    89 	
    90 	// Do NOT use for CRYPTOGRAPHY without securely hashing several returned
    91 	// values together, otherwise the generator state can be learned after
    92 	// reading 624 consecutive values.
    93 	
    94 	// Access to 32-bit random numbers
    95 	double rand();                          // real number in [0,1]
    96 	double rand( const double& n );         // real number in [0,n]
    97 	double randExc();                       // real number in [0,1)
    98 	double randExc( const double& n );      // real number in [0,n)
    99 	double randDblExc();                    // real number in (0,1)
   100 	double randDblExc( const double& n );   // real number in (0,n)
   101 	uint32 randInt();                       // integer in [0,2^32-1]
   102 	uint32 randInt( const uint32& n );      // integer in [0,n] for n < 2^32
   103 	double operator()() { return rand(); }  // same as rand()
   104 	
   105 	// Access to 53-bit random numbers (capacity of IEEE double precision)
   106 	double rand53();  // real number in [0,1)
   107 	
   108 	// Access to nonuniform random number distributions
   109 	double randNorm( const double& mean = 0.0, const double& variance = 0.0 );
   110 	
   111 	// Re-seeding functions with same behavior as initializers
   112 	void seed( const uint32 oneSeed );
   113 	void seed( uint32 *const bigSeed, const uint32 seedLength = N );
   114 	void seed();
   115 	
   116 	// Saving and loading generator state
   117 	void save( uint32* saveArray ) const;  // to array of size SAVE
   118 	void load( uint32 *const loadArray );  // from such array
   119 protected:
   120 	void initialize( const uint32 oneSeed );
   121 	void reload();
   122 	uint32 hiBit( const uint32& u ) const { return u & 0x80000000UL; }
   123 	uint32 loBit( const uint32& u ) const { return u & 0x00000001UL; }
   124 	uint32 loBits( const uint32& u ) const { return u & 0x7fffffffUL; }
   125 	uint32 mixBits( const uint32& u, const uint32& v ) const
   126 		{ return hiBit(u) | loBits(v); }
   127 	uint32 twist( const uint32& m, const uint32& s0, const uint32& s1 ) const
   128 		{ return m ^ (mixBits(s0,s1)>>1) ^ (-loBit(s1) & 0x9908b0dfUL); }
   129 	static uint32 hash( time_t t, clock_t c );
   130 };
   131 
   132 
   133 inline MTRand::MTRand( const uint32& oneSeed )
   134 	{ seed(oneSeed); }
   135 
   136 inline MTRand::MTRand( uint32 *const bigSeed, const uint32 seedLength )
   137 	{ seed(bigSeed,seedLength); }
   138 
   139 inline MTRand::MTRand()
   140 	{ seed(); }
   141 
   142 inline double MTRand::rand()
   143 	{ return double(randInt()) * (1.0/4294967295.0); }
   144 
   145 inline double MTRand::rand( const double& n )
   146 	{ return rand() * n; }
   147 
   148 inline double MTRand::randExc()
   149 	{ return double(randInt()) * (1.0/4294967296.0); }
   150 
   151 inline double MTRand::randExc( const double& n )
   152 	{ return randExc() * n; }
   153 
   154 inline double MTRand::randDblExc()
   155 	{ return ( double(randInt()) + 0.5 ) * (1.0/4294967296.0); }
   156 
   157 inline double MTRand::randDblExc( const double& n )
   158 	{ return randDblExc() * n; }
   159 
   160 inline double MTRand::rand53()
   161 {
   162 	uint32 a = randInt() >> 5, b = randInt() >> 6;
   163 	return ( a * 67108864.0 + b ) * (1.0/9007199254740992.0);  // by Isaku Wada
   164 }
   165 
   166 inline double MTRand::randNorm( const double& mean, const double& variance )
   167 {
   168 	// Return a real number from a normal (Gaussian) distribution with given
   169 	// mean and variance by Box-Muller method
   170 	double r = sqrt( -2.0 * log( 1.0-randDblExc()) ) * variance;
   171 	double phi = 2.0 * 3.14159265358979323846264338328 * randExc();
   172 	return mean + r * cos(phi);
   173 }
   174 
   175 inline MTRand::uint32 MTRand::randInt()
   176 {
   177 	// Pull a 32-bit integer from the generator state
   178 	// Every other access function simply transforms the numbers extracted here
   179 	
   180 	if( left == 0 ) reload();
   181 	--left;
   182 		
   183 	register uint32 s1;
   184 	s1 = *pNext++;
   185 	s1 ^= (s1 >> 11);
   186 	s1 ^= (s1 <<  7) & 0x9d2c5680UL;
   187 	s1 ^= (s1 << 15) & 0xefc60000UL;
   188 	return ( s1 ^ (s1 >> 18) );
   189 }
   190 
   191 inline MTRand::uint32 MTRand::randInt( const uint32& n )
   192 {
   193 	// Find which bits are used in n
   194 	// Optimized by Magnus Jonsson ([email protected])
   195 	uint32 used = n;
   196 	used |= used >> 1;
   197 	used |= used >> 2;
   198 	used |= used >> 4;
   199 	used |= used >> 8;
   200 	used |= used >> 16;
   201 	
   202 	// Draw numbers until one is found in [0,n]
   203 	uint32 i;
   204 	do
   205 		i = randInt() & used;  // toss unused bits to shorten search
   206 	while( i > n );
   207 	return i;
   208 }
   209 
   210 
   211 inline void MTRand::seed( const uint32 oneSeed )
   212 {
   213 	// Seed the generator with a simple uint32
   214 	initialize(oneSeed);
   215 	reload();
   216 }
   217 
   218 
   219 inline void MTRand::seed( uint32 *const bigSeed, const uint32 seedLength )
   220 {
   221 	// Seed the generator with an array of uint32's
   222 	// There are 2^19937-1 possible initial states.  This function allows
   223 	// all of those to be accessed by providing at least 19937 bits (with a
   224 	// default seed length of N = 624 uint32's).  Any bits above the lower 32
   225 	// in each element are discarded.
   226 	// Just call seed() if you want to get array from /dev/urandom
   227 	initialize(19650218UL);
   228 	register int i = 1;
   229 	register uint32 j = 0;
   230 	register int k = ( N > seedLength ? N : seedLength );
   231 	for( ; k; --k )
   232 	{
   233 		state[i] =
   234 			state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1664525UL );
   235 		state[i] += ( bigSeed[j] & 0xffffffffUL ) + j;
   236 		state[i] &= 0xffffffffUL;
   237 		++i;  ++j;
   238 		if( i >= N ) { state[0] = state[N-1];  i = 1; }
   239 		if( j >= seedLength ) j = 0;
   240 	}
   241 	for( k = N - 1; k; --k )
   242 	{
   243 		state[i] =
   244 			state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1566083941UL );
   245 		state[i] -= i;
   246 		state[i] &= 0xffffffffUL;
   247 		++i;
   248 		if( i >= N ) { state[0] = state[N-1];  i = 1; }
   249 	}
   250 	state[0] = 0x80000000UL;  // MSB is 1, assuring non-zero initial array
   251 	reload();
   252 }
   253 
   254 
   255 inline void MTRand::seed()
   256 {
   257 	// Seed the generator with an array from /dev/urandom if available
   258 	// Otherwise use a hash of time() and clock() values
   259 	
   260 	// First try getting an array from /dev/urandom
   261 	FILE* urandom = fopen( "/dev/urandom", "rb" );
   262 	if( urandom )
   263 	{
   264 		uint32 bigSeed[N];
   265 		register uint32 *s = bigSeed;
   266 		register int i = N;
   267 		register bool success = true;
   268 		while( success && i-- )
   269 			success = fread( s++, sizeof(uint32), 1, urandom );
   270 		fclose(urandom);
   271 		if( success ) { seed( bigSeed, N );  return; }
   272 	}
   273 	
   274 	// Was not successful, so use time() and clock() instead
   275 	seed( hash( time(NULL), clock() ) );
   276 }
   277 
   278 
   279 inline void MTRand::initialize( const uint32 seed )
   280 {
   281 	// Initialize generator state with seed
   282 	// See Knuth TAOCP Vol 2, 3rd Ed, p.106 for multiplier.
   283 	// In previous versions, most significant bits (MSBs) of the seed affect
   284 	// only MSBs of the state array.  Modified 9 Jan 2002 by Makoto Matsumoto.
   285 	register uint32 *s = state;
   286 	register uint32 *r = state;
   287 	register int i = 1;
   288 	*s++ = seed & 0xffffffffUL;
   289 	for( ; i < N; ++i )
   290 	{
   291 		*s++ = ( 1812433253UL * ( *r ^ (*r >> 30) ) + i ) & 0xffffffffUL;
   292 		r++;
   293 	}
   294 }
   295 
   296 
   297 inline void MTRand::reload()
   298 {
   299 	// Generate N new values in state
   300 	// Made clearer and faster by Matthew Bellew ([email protected])
   301 	register uint32 *p = state;
   302 	register int i;
   303 	for( i = N - M; i--; ++p )
   304 		*p = twist( p[M], p[0], p[1] );
   305 	for( i = M; --i; ++p )
   306 		*p = twist( p[M-N], p[0], p[1] );
   307 	*p = twist( p[M-N], p[0], state[0] );
   308 
   309 	left = N, pNext = state;
   310 }
   311 
   312 
   313 inline MTRand::uint32 MTRand::hash( time_t t, clock_t c )
   314 {
   315 	// Get a uint32 from t and c
   316 	// Better than uint32(x) in case x is floating point in [0,1]
   317 	// Based on code by Lawrence Kirby ([email protected])
   318 
   319 	static uint32 differ = 0;  // guarantee time-based seeds will change
   320 
   321 	uint32 h1 = 0;
   322 	unsigned char *p = (unsigned char *) &t;
   323 	for( size_t i = 0; i < sizeof(t); ++i )
   324 	{
   325 		h1 *= UCHAR_MAX + 2U;
   326 		h1 += p[i];
   327 	}
   328 	uint32 h2 = 0;
   329 	p = (unsigned char *) &c;
   330 	for( size_t j = 0; j < sizeof(c); ++j )
   331 	{
   332 		h2 *= UCHAR_MAX + 2U;
   333 		h2 += p[j];
   334 	}
   335 	return ( h1 + differ++ ) ^ h2;
   336 }
   337 
   338 
   339 inline void MTRand::save( uint32* saveArray ) const
   340 {
   341 	register uint32 *sa = saveArray;
   342 	register const uint32 *s = state;
   343 	register int i = N;
   344 	for( ; i--; *sa++ = *s++ ) {}
   345 	*sa = left;
   346 }
   347 
   348 
   349 inline void MTRand::load( uint32 *const loadArray )
   350 {
   351 	register uint32 *s = state;
   352 	register uint32 *la = loadArray;
   353 	register int i = N;
   354 	for( ; i--; *s++ = *la++ ) {}
   355 	left = *la;
   356 	pNext = &state[N-left];
   357 }
   358 
   359 #endif  // MERSENNETWISTER_H
   360 
   361 // Change log:
   362 //
   363 // v0.1 - First release on 15 May 2000
   364 //      - Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus
   365 //      - Translated from C to C++
   366 //      - Made completely ANSI compliant
   367 //      - Designed convenient interface for initialization, seeding, and
   368 //        obtaining numbers in default or user-defined ranges
   369 //      - Added automatic seeding from /dev/urandom or time() and clock()
   370 //      - Provided functions for saving and loading generator state
   371 //
   372 // v0.2 - Fixed bug which reloaded generator one step too late
   373 //
   374 // v0.3 - Switched to clearer, faster reload() code from Matthew Bellew
   375 //
   376 // v0.4 - Removed trailing newline in saved generator format to be consistent
   377 //        with output format of built-in types
   378 //
   379 // v0.5 - Improved portability by replacing static const int's with enum's and
   380 //        clarifying return values in seed(); suggested by Eric Heimburg
   381 //      - Removed MAXINT constant; use 0xffffffffUL instead
   382 //
   383 // v0.6 - Eliminated seed overflow when uint32 is larger than 32 bits
   384 //      - Changed integer [0,n] generator to give better uniformity
   385 //
   386 // v0.7 - Fixed operator precedence ambiguity in reload()
   387 //      - Added access for real numbers in (0,1) and (0,n)
   388 //
   389 // v0.8 - Included time.h header to properly support time_t and clock_t
   390 //
   391 // v1.0 - Revised seeding to match 26 Jan 2002 update of Nishimura and Matsumoto
   392 //      - Allowed for seeding with arrays of any length
   393 //      - Added access for real numbers in [0,1) with 53-bit resolution
   394 //      - Added access for real numbers from normal (Gaussian) distributions
   395 //      - Increased overall speed by optimizing twist()
   396 //      - Doubled speed of integer [0,n] generation
   397 //      - Fixed out-of-range number generation on 64-bit machines
   398 //      - Improved portability by substituting literal constants for long enum's
   399 //      - Changed license from GNU LGPL to BSD