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