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