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