SUMO - Simulation of Urban MObility
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
MersenneTwister.h
Go to the documentation of this file.
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 rjwagner@writeme.com
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: matumoto@math.keio.ac.jp
52 // with an appropriate reference to your work.
53 //
54 // It would be nice to CC: rjwagner@writeme.com and Cokus@math.washington.edu
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 #ifdef _MSC_VER // !!! mb pragmas added 19.02.2007
64 #pragma warning(disable: 4146)
65 #pragma warning(disable: 4996)
66 #endif
67 
68 #include <iostream>
69 #include <limits.h>
70 #include <stdio.h>
71 #include <time.h>
72 #include <math.h>
73 
74 class MTRand {
75 // Data
76 public:
77  typedef unsigned long uint32; // unsigned integer type, at least 32 bits
78 
79  enum { N = 624 }; // length of state vector
80  enum { SAVE = N + 1 }; // length of array for save()
81 
82 protected:
83  enum { M = 397 }; // period parameter
84 
85  uint32 state[N]; // internal state
86  uint32 *pNext; // next value to get from state
87  int left; // number of values left before reload needed
88 
89 
90 //Methods
91 public:
92  MTRand( const uint32& oneSeed ); // initialize with a simple uint32
93  MTRand( uint32 *const bigSeed, uint32 const seedLength = N ); // or an array
94  MTRand(); // auto-initialize with /dev/urandom or time() and clock()
95 
96  // Do NOT use for CRYPTOGRAPHY without securely hashing several returned
97  // values together, otherwise the generator state can be learned after
98  // reading 624 consecutive values.
99 
100  // Access to 32-bit random numbers
101  double rand(); // real number in [0,1]
102  double rand( const double& n ); // real number in [0,n]
103  double randExc(); // real number in [0,1)
104  double randExc( const double& n ); // real number in [0,n)
105  double randDblExc(); // real number in (0,1)
106  double randDblExc( const double& n ); // real number in (0,n)
107  uint32 randInt(); // integer in [0,2^32-1]
108  uint32 randInt( const uint32& n ); // integer in [0,n] for n < 2^32
109  double operator()() { return rand(); } // same as rand()
110 
111  // Access to 53-bit random numbers (capacity of IEEE double precision)
112  double rand53(); // real number in [0,1)
113 
114  // Access to nonuniform random number distributions
115  double randNorm( const double& mean = 0.0, const double& variance = 0.0 );
116 
117  // Re-seeding functions with same behavior as initializers
118  void seed( const uint32 oneSeed );
119  void seed( uint32 *const bigSeed, const uint32 seedLength = N );
120  void seed();
121 
122  // Saving and loading generator state
123  void save( uint32* saveArray ) const; // to array of size SAVE
124  void load( uint32 *const loadArray ); // from such array
125  friend std::ostream& operator<<( std::ostream& os, const MTRand& mtrand );
126  friend std::istream& operator>>( std::istream& is, MTRand& mtrand );
127 
128  static uint32 hash( time_t t, clock_t c ); // !!! dk moved to public
129 
130 protected:
131  void initialize( const uint32 oneSeed );
132  void reload();
133  uint32 hiBit( const uint32& u ) const { return u & 0x80000000UL; }
134  uint32 loBits( const uint32& u ) const { return u & 0x7fffffffUL; }
135  uint32 mixBits( const uint32& u, const uint32& v ) const
136  { return hiBit(u) | loBits(v); }
137  uint32 twist( const uint32& m, const uint32& s0, const uint32& s1 ) const
138  { return m ^ (mixBits(s0,s1)>>1) ^ (s1 & 1UL ? 0x9908b0dfUL : 0); }
139  // !!! mb changed -(s1&1)&a to the ? operator to remove negation of unsigned value
140 };
141 
142 
143 inline MTRand::MTRand( const uint32& oneSeed )
144  { seed(oneSeed); }
145 
146 inline MTRand::MTRand( uint32 *const bigSeed, const uint32 seedLength )
147  { seed(bigSeed,seedLength); }
148 
150  { seed(); }
151 
152 inline double MTRand::rand()
153  { return double(randInt()) * (1.0/4294967295.0); }
154 
155 inline double MTRand::rand( const double& n )
156  { return rand() * n; }
157 
158 inline double MTRand::randExc()
159  { return double(randInt()) * (1.0/4294967296.0); }
160 
161 inline double MTRand::randExc( const double& n )
162  { return randExc() * n; }
163 
164 inline double MTRand::randDblExc()
165  { return ( double(randInt()) + 0.5 ) * (1.0/4294967296.0); }
166 
167 inline double MTRand::randDblExc( const double& n )
168  { return randDblExc() * n; }
169 
170 inline double MTRand::rand53()
171 {
172  uint32 a = randInt() >> 5, b = randInt() >> 6;
173  return ( a * 67108864.0 + b ) * (1.0/9007199254740992.0); // by Isaku Wada
174 }
175 
176 inline double MTRand::randNorm( const double& mean, const double& variance )
177 {
178  // Return a real number from a normal (Gaussian) distribution with given
179  // mean and variance by Box-Muller method
180  double r = sqrt( -2.0 * log( 1.0-randDblExc()) ) * variance;
181  double phi = 2.0 * 3.14159265358979323846264338328 * randExc();
182  return mean + r * cos(phi);
183 }
184 
186 {
187  // Pull a 32-bit integer from the generator state
188  // Every other access function simply transforms the numbers extracted here
189 
190  if( left == 0 ) reload();
191  --left;
192 
193  register uint32 s1;
194  s1 = *pNext++;
195  s1 ^= (s1 >> 11);
196  s1 ^= (s1 << 7) & 0x9d2c5680UL;
197  s1 ^= (s1 << 15) & 0xefc60000UL;
198  return ( s1 ^ (s1 >> 18) );
199 }
200 
202 {
203  // Find which bits are used in n
204  // Optimized by Magnus Jonsson (magnus@smartelectronix.com)
205  uint32 used = n;
206  used |= used >> 1;
207  used |= used >> 2;
208  used |= used >> 4;
209  used |= used >> 8;
210  used |= used >> 16;
211 
212  // Draw numbers until one is found in [0,n]
213  uint32 i;
214  do
215  i = randInt() & used; // toss unused bits to shorten search
216  while( i > n );
217  return i;
218 }
219 
220 
221 inline void MTRand::seed( const uint32 oneSeed )
222 {
223  // Seed the generator with a simple uint32
224  initialize(oneSeed);
225  reload();
226 }
227 
228 
229 inline void MTRand::seed( uint32 *const bigSeed, const uint32 seedLength )
230 {
231  // Seed the generator with an array of uint32's
232  // There are 2^19937-1 possible initial states. This function allows
233  // all of those to be accessed by providing at least 19937 bits (with a
234  // default seed length of N = 624 uint32's). Any bits above the lower 32
235  // in each element are discarded.
236  // Just call seed() if you want to get array from /dev/urandom
237  initialize(19650218UL);
238  register int i = 1;
239  register uint32 j = 0;
240  register uint32 k = N;
241  if( seedLength > k ) k = seedLength;
242  for( ; k; --k )
243  {
244  state[i] =
245  state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1664525UL );
246  state[i] += ( bigSeed[j] & 0xffffffffUL ) + j;
247  state[i] &= 0xffffffffUL;
248  ++i; ++j;
249  if( i >= N ) { state[0] = state[N-1]; i = 1; }
250  if( j >= seedLength ) j = 0;
251  }
252  for( k = N - 1; k; --k )
253  {
254  state[i] =
255  state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1566083941UL );
256  state[i] -= i;
257  state[i] &= 0xffffffffUL;
258  ++i;
259  if( i >= N ) { state[0] = state[N-1]; i = 1; }
260  }
261  state[0] = 0x80000000UL; // MSB is 1, assuring non-zero initial array
262  reload();
263 }
264 
265 
266 inline void MTRand::seed()
267 {
268  // Seed the generator with an array from /dev/urandom if available
269  // Otherwise use a hash of time() and clock() values
270 
271  // First try getting an array from /dev/urandom
272  FILE* urandom = fopen( "/dev/urandom", "rb" );
273  if( urandom )
274  {
275  uint32 bigSeed[N];
276  register uint32 *s = bigSeed;
277  register int i = N;
278  register bool success = true;
279  while( success && i-- )
280  success = fread( s++, sizeof(uint32), 1, urandom )!=0; // !!! dk 16.02.2007
281  fclose(urandom);
282  if( success ) { seed( bigSeed, N ); return; }
283  }
284 
285  // Was not successful, so use time() and clock() instead
286  seed( hash( time(NULL), clock() ) );
287 }
288 
289 
290 inline void MTRand::initialize( const uint32 seed )
291 {
292  // Initialize generator state with seed
293  // See Knuth TAOCP Vol 2, 3rd Ed, p.106 for multiplier.
294  // In previous versions, most significant bits (MSBs) of the seed affect
295  // only MSBs of the state array. Modified 9 Jan 2002 by Makoto Matsumoto.
296  register uint32 *s = state;
297  register uint32 *r = state;
298  register int i = 1;
299  *s++ = seed & 0xffffffffUL;
300  for( ; i < N; ++i )
301  {
302  *s++ = ( 1812433253UL * ( *r ^ (*r >> 30) ) + i ) & 0xffffffffUL;
303  r++;
304  }
305 }
306 
307 
308 inline void MTRand::reload()
309 {
310  // Generate N new values in state
311  // Made clearer and faster by Matthew Bellew (matthew.bellew@home.com)
312  register uint32 *p = state;
313  register int i;
314  for( i = N - M; i--; ++p )
315  *p = twist( p[M], p[0], p[1] );
316  for( i = M; --i; ++p )
317  *p = twist( p[M-N], p[0], p[1] );
318  *p = twist( p[M-N], p[0], state[0] );
319 
320  left = N, pNext = state;
321 }
322 
323 
324 inline MTRand::uint32 MTRand::hash( time_t t, clock_t c )
325 {
326  // Get a uint32 from t and c
327  // Better than uint32(x) in case x is floating point in [0,1]
328  // Based on code by Lawrence Kirby (fred@genesis.demon.co.uk)
329 
330  static uint32 differ = 0; // guarantee time-based seeds will change
331 
332  uint32 h1 = 0;
333  unsigned char *p = (unsigned char *) &t;
334  for( size_t i = 0; i < sizeof(t); ++i )
335  {
336  h1 *= UCHAR_MAX + 2U;
337  h1 += p[i];
338  }
339  uint32 h2 = 0;
340  p = (unsigned char *) &c;
341  for( size_t j = 0; j < sizeof(c); ++j )
342  {
343  h2 *= UCHAR_MAX + 2U;
344  h2 += p[j];
345  }
346  return ( h1 + differ++ ) ^ h2;
347 }
348 
349 
350 inline void MTRand::save( uint32* saveArray ) const
351 {
352  register uint32 *sa = saveArray;
353  register const uint32 *s = state;
354  register int i = N;
355  for( ; i--; *sa++ = *s++ ) {}
356  *sa = left;
357 }
358 
359 
360 inline void MTRand::load( uint32 *const loadArray )
361 {
362  register uint32 *s = state;
363  register uint32 *la = loadArray;
364  register int i = N;
365  for( ; i--; *s++ = *la++ ) {}
366  left = *la;
367  pNext = &state[N-left];
368 }
369 
370 
371 inline std::ostream& operator<<( std::ostream& os, const MTRand& mtrand )
372 {
373  register const MTRand::uint32 *s = mtrand.state;
374  register int i = mtrand.N;
375  for( ; i--; os << *s++ << "\t" ) {}
376  return os << mtrand.left;
377 }
378 
379 
380 inline std::istream& operator>>( std::istream& is, MTRand& mtrand )
381 {
382  register MTRand::uint32 *s = mtrand.state;
383  register int i = mtrand.N;
384  for( ; i--; is >> *s++ ) {}
385  is >> mtrand.left;
386  mtrand.pNext = &mtrand.state[mtrand.N-mtrand.left];
387  return is;
388 }
389 
390 #endif // MERSENNETWISTER_H
391 
392 // Change log:
393 //
394 // v0.1 - First release on 15 May 2000
395 // - Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus
396 // - Translated from C to C++
397 // - Made completely ANSI compliant
398 // - Designed convenient interface for initialization, seeding, and
399 // obtaining numbers in default or user-defined ranges
400 // - Added automatic seeding from /dev/urandom or time() and clock()
401 // - Provided functions for saving and loading generator state
402 //
403 // v0.2 - Fixed bug which reloaded generator one step too late
404 //
405 // v0.3 - Switched to clearer, faster reload() code from Matthew Bellew
406 //
407 // v0.4 - Removed trailing newline in saved generator format to be consistent
408 // with output format of built-in types
409 //
410 // v0.5 - Improved portability by replacing static const int's with enum's and
411 // clarifying return values in seed(); suggested by Eric Heimburg
412 // - Removed MAXINT constant; use 0xffffffffUL instead
413 //
414 // v0.6 - Eliminated seed overflow when uint32 is larger than 32 bits
415 // - Changed integer [0,n] generator to give better uniformity
416 //
417 // v0.7 - Fixed operator precedence ambiguity in reload()
418 // - Added access for real numbers in (0,1) and (0,n)
419 //
420 // v0.8 - Included time.h header to properly support time_t and clock_t
421 //
422 // v1.0 - Revised seeding to match 26 Jan 2002 update of Nishimura and Matsumoto
423 // - Allowed for seeding with arrays of any length
424 // - Added access for real numbers in [0,1) with 53-bit resolution
425 // - Added access for real numbers from normal (Gaussian) distributions
426 // - Increased overall speed by optimizing twist()
427 // - Doubled speed of integer [0,n] generation
428 // - Fixed out-of-range number generation on 64-bit machines
429 // - Improved portability by substituting literal constants for long enum's
430 // - Changed license from GNU LGPL to BSD
double rand()
void load(uint32 *const loadArray)
friend std::istream & operator>>(std::istream &is, MTRand &mtrand)
uint32 twist(const uint32 &m, const uint32 &s0, const uint32 &s1) const
void reload()
double operator()()
uint32 mixBits(const uint32 &u, const uint32 &v) const
static uint32 hash(time_t t, clock_t c)
uint32 state[N]
unsigned long uint32
void initialize(const uint32 oneSeed)
uint32 loBits(const uint32 &u) const
std::istream & operator>>(std::istream &is, MTRand &mtrand)
uint32 randInt()
void seed()
double randNorm(const double &mean=0.0, const double &variance=0.0)
void save(uint32 *saveArray) const
uint32 hiBit(const uint32 &u) const
double randExc()
friend std::ostream & operator<<(std::ostream &os, const MTRand &mtrand)
double randDblExc()
std::ostream & operator<<(std::ostream &os, const MTRand &mtrand)
double rand53()
uint32 * pNext