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