SUMO - Simulation of Urban MObility
|
00001 // MersenneTwister.h 00002 // Mersenne Twister random number generator -- a C++ class MTRand 00003 // Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus 00004 // Richard J. Wagner v1.0 15 May 2003 rjwagner@writeme.com 00005 00006 // The Mersenne Twister is an algorithm for generating random numbers. It 00007 // was designed with consideration of the flaws in various other generators. 00008 // The period, 2^19937-1, and the order of equidistribution, 623 dimensions, 00009 // are far greater. The generator is also fast; it avoids multiplication and 00010 // division, and it benefits from caches and pipelines. For more information 00011 // see the inventors' web page at http://www.math.keio.ac.jp/~matumoto/emt.html 00012 00013 // Reference 00014 // M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-Dimensionally 00015 // Equidistributed Uniform Pseudo-Random Number Generator", ACM Transactions on 00016 // Modeling and Computer Simulation, Vol. 8, No. 1, January 1998, pp 3-30. 00017 00018 // Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, 00019 // Copyright (C) 2000 - 2003, Richard J. Wagner 00020 // All rights reserved. 00021 // 00022 // Redistribution and use in source and binary forms, with or without 00023 // modification, are permitted provided that the following conditions 00024 // are met: 00025 // 00026 // 1. Redistributions of source code must retain the above copyright 00027 // notice, this list of conditions and the following disclaimer. 00028 // 00029 // 2. Redistributions in binary form must reproduce the above copyright 00030 // notice, this list of conditions and the following disclaimer in the 00031 // documentation and/or other materials provided with the distribution. 00032 // 00033 // 3. The names of its contributors may not be used to endorse or promote 00034 // products derived from this software without specific prior written 00035 // permission. 00036 // 00037 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 00038 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 00039 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 00040 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 00041 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 00042 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 00043 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 00044 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 00045 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 00046 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 00047 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 00048 00049 // The original code included the following notice: 00050 // 00051 // When you use this, send an email to: matumoto@math.keio.ac.jp 00052 // with an appropriate reference to your work. 00053 // 00054 // It would be nice to CC: rjwagner@writeme.com and Cokus@math.washington.edu 00055 // when you write. 00056 00057 #ifndef MERSENNETWISTER_H 00058 #define MERSENNETWISTER_H 00059 00060 // Not thread safe (unless auto-initialization is avoided and each thread has 00061 // its own MTRand object) 00062 00063 #ifdef _MSC_VER // !!! mb pragmas added 19.02.2007 00064 #pragma warning(disable: 4146) 00065 #pragma warning(disable: 4996) 00066 #endif 00067 00068 #include <iostream> 00069 #include <limits.h> 00070 #include <stdio.h> 00071 #include <time.h> 00072 #include <math.h> 00073 00074 class MTRand { 00075 // Data 00076 public: 00077 typedef unsigned long uint32; // unsigned integer type, at least 32 bits 00078 00079 enum { N = 624 }; // length of state vector 00080 enum { SAVE = N + 1 }; // length of array for save() 00081 00082 protected: 00083 enum { M = 397 }; // period parameter 00084 00085 uint32 state[N]; // internal state 00086 uint32 *pNext; // next value to get from state 00087 int left; // number of values left before reload needed 00088 00089 00090 //Methods 00091 public: 00092 MTRand( const uint32& oneSeed ); // initialize with a simple uint32 00093 MTRand( uint32 *const bigSeed, uint32 const seedLength = N ); // or an array 00094 MTRand(); // auto-initialize with /dev/urandom or time() and clock() 00095 00096 // Do NOT use for CRYPTOGRAPHY without securely hashing several returned 00097 // values together, otherwise the generator state can be learned after 00098 // reading 624 consecutive values. 00099 00100 // Access to 32-bit random numbers 00101 double rand(); // real number in [0,1] 00102 double rand( const double& n ); // real number in [0,n] 00103 double randExc(); // real number in [0,1) 00104 double randExc( const double& n ); // real number in [0,n) 00105 double randDblExc(); // real number in (0,1) 00106 double randDblExc( const double& n ); // real number in (0,n) 00107 uint32 randInt(); // integer in [0,2^32-1] 00108 uint32 randInt( const uint32& n ); // integer in [0,n] for n < 2^32 00109 double operator()() { return rand(); } // same as rand() 00110 00111 // Access to 53-bit random numbers (capacity of IEEE double precision) 00112 double rand53(); // real number in [0,1) 00113 00114 // Access to nonuniform random number distributions 00115 double randNorm( const double& mean = 0.0, const double& variance = 0.0 ); 00116 00117 // Re-seeding functions with same behavior as initializers 00118 void seed( const uint32 oneSeed ); 00119 void seed( uint32 *const bigSeed, const uint32 seedLength = N ); 00120 void seed(); 00121 00122 // Saving and loading generator state 00123 void save( uint32* saveArray ) const; // to array of size SAVE 00124 void load( uint32 *const loadArray ); // from such array 00125 friend std::ostream& operator<<( std::ostream& os, const MTRand& mtrand ); 00126 friend std::istream& operator>>( std::istream& is, MTRand& mtrand ); 00127 00128 protected: 00129 void initialize( const uint32 oneSeed ); 00130 void reload(); 00131 uint32 hiBit( const uint32& u ) const { return u & 0x80000000UL; } 00132 uint32 loBit( const uint32& u ) const { return u & 0x00000001UL; } 00133 uint32 loBits( const uint32& u ) const { return u & 0x7fffffffUL; } 00134 uint32 mixBits( const uint32& u, const uint32& v ) const 00135 { return hiBit(u) | loBits(v); } 00136 uint32 twist( const uint32& m, const uint32& s0, const uint32& s1 ) const 00137 { return m ^ (mixBits(s0,s1)>>1) ^ (-loBit(s1) & 0x9908b0dfUL); } 00138 static uint32 hash( time_t t, clock_t c ); 00139 }; 00140 00141 00142 inline MTRand::MTRand( const uint32& oneSeed ) 00143 { seed(oneSeed); } 00144 00145 inline MTRand::MTRand( uint32 *const bigSeed, const uint32 seedLength ) 00146 { seed(bigSeed,seedLength); } 00147 00148 inline MTRand::MTRand() 00149 { seed(); } 00150 00151 inline double MTRand::rand() 00152 { return double(randInt()) * (1.0/4294967295.0); } 00153 00154 inline double MTRand::rand( const double& n ) 00155 { return rand() * n; } 00156 00157 inline double MTRand::randExc() 00158 { return double(randInt()) * (1.0/4294967296.0); } 00159 00160 inline double MTRand::randExc( const double& n ) 00161 { return randExc() * n; } 00162 00163 inline double MTRand::randDblExc() 00164 { return ( double(randInt()) + 0.5 ) * (1.0/4294967296.0); } 00165 00166 inline double MTRand::randDblExc( const double& n ) 00167 { return randDblExc() * n; } 00168 00169 inline double MTRand::rand53() 00170 { 00171 uint32 a = randInt() >> 5, b = randInt() >> 6; 00172 return ( a * 67108864.0 + b ) * (1.0/9007199254740992.0); // by Isaku Wada 00173 } 00174 00175 inline double MTRand::randNorm( const double& mean, const double& variance ) 00176 { 00177 // Return a real number from a normal (Gaussian) distribution with given 00178 // mean and variance by Box-Muller method 00179 double r = sqrt( -2.0 * log( 1.0-randDblExc()) ) * variance; 00180 double phi = 2.0 * 3.14159265358979323846264338328 * randExc(); 00181 return mean + r * cos(phi); 00182 } 00183 00184 inline MTRand::uint32 MTRand::randInt() 00185 { 00186 // Pull a 32-bit integer from the generator state 00187 // Every other access function simply transforms the numbers extracted here 00188 00189 if( left == 0 ) reload(); 00190 --left; 00191 00192 register uint32 s1; 00193 s1 = *pNext++; 00194 s1 ^= (s1 >> 11); 00195 s1 ^= (s1 << 7) & 0x9d2c5680UL; 00196 s1 ^= (s1 << 15) & 0xefc60000UL; 00197 return ( s1 ^ (s1 >> 18) ); 00198 } 00199 00200 inline MTRand::uint32 MTRand::randInt( const uint32& n ) 00201 { 00202 // Find which bits are used in n 00203 // Optimized by Magnus Jonsson (magnus@smartelectronix.com) 00204 uint32 used = n; 00205 used |= used >> 1; 00206 used |= used >> 2; 00207 used |= used >> 4; 00208 used |= used >> 8; 00209 used |= used >> 16; 00210 00211 // Draw numbers until one is found in [0,n] 00212 uint32 i; 00213 do 00214 i = randInt() & used; // toss unused bits to shorten search 00215 while( i > n ); 00216 return i; 00217 } 00218 00219 00220 inline void MTRand::seed( const uint32 oneSeed ) 00221 { 00222 // Seed the generator with a simple uint32 00223 initialize(oneSeed); 00224 reload(); 00225 } 00226 00227 00228 inline void MTRand::seed( uint32 *const bigSeed, const uint32 seedLength ) 00229 { 00230 // Seed the generator with an array of uint32's 00231 // There are 2^19937-1 possible initial states. This function allows 00232 // all of those to be accessed by providing at least 19937 bits (with a 00233 // default seed length of N = 624 uint32's). Any bits above the lower 32 00234 // in each element are discarded. 00235 // Just call seed() if you want to get array from /dev/urandom 00236 initialize(19650218UL); 00237 register int i = 1; 00238 register uint32 j = 0; 00239 register uint32 k = N; 00240 if( seedLength > k ) k = seedLength; 00241 for( ; k; --k ) 00242 { 00243 state[i] = 00244 state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1664525UL ); 00245 state[i] += ( bigSeed[j] & 0xffffffffUL ) + j; 00246 state[i] &= 0xffffffffUL; 00247 ++i; ++j; 00248 if( i >= N ) { state[0] = state[N-1]; i = 1; } 00249 if( j >= seedLength ) j = 0; 00250 } 00251 for( k = N - 1; k; --k ) 00252 { 00253 state[i] = 00254 state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1566083941UL ); 00255 state[i] -= i; 00256 state[i] &= 0xffffffffUL; 00257 ++i; 00258 if( i >= N ) { state[0] = state[N-1]; i = 1; } 00259 } 00260 state[0] = 0x80000000UL; // MSB is 1, assuring non-zero initial array 00261 reload(); 00262 } 00263 00264 00265 inline void MTRand::seed() 00266 { 00267 // Seed the generator with an array from /dev/urandom if available 00268 // Otherwise use a hash of time() and clock() values 00269 00270 // First try getting an array from /dev/urandom 00271 FILE* urandom = fopen( "/dev/urandom", "rb" ); 00272 if( urandom ) 00273 { 00274 uint32 bigSeed[N]; 00275 register uint32 *s = bigSeed; 00276 register int i = N; 00277 register bool success = true; 00278 while( success && i-- ) 00279 success = fread( s++, sizeof(uint32), 1, urandom )!=0; // !!! dk 16.02.2007 00280 fclose(urandom); 00281 if( success ) { seed( bigSeed, N ); return; } 00282 } 00283 00284 // Was not successful, so use time() and clock() instead 00285 seed( hash( time(NULL), clock() ) ); 00286 } 00287 00288 00289 inline void MTRand::initialize( const uint32 seed ) 00290 { 00291 // Initialize generator state with seed 00292 // See Knuth TAOCP Vol 2, 3rd Ed, p.106 for multiplier. 00293 // In previous versions, most significant bits (MSBs) of the seed affect 00294 // only MSBs of the state array. Modified 9 Jan 2002 by Makoto Matsumoto. 00295 register uint32 *s = state; 00296 register uint32 *r = state; 00297 register int i = 1; 00298 *s++ = seed & 0xffffffffUL; 00299 for( ; i < N; ++i ) 00300 { 00301 *s++ = ( 1812433253UL * ( *r ^ (*r >> 30) ) + i ) & 0xffffffffUL; 00302 r++; 00303 } 00304 } 00305 00306 00307 inline void MTRand::reload() 00308 { 00309 // Generate N new values in state 00310 // Made clearer and faster by Matthew Bellew (matthew.bellew@home.com) 00311 register uint32 *p = state; 00312 register int i; 00313 for( i = N - M; i--; ++p ) 00314 *p = twist( p[M], p[0], p[1] ); 00315 for( i = M; --i; ++p ) 00316 *p = twist( p[M-N], p[0], p[1] ); 00317 *p = twist( p[M-N], p[0], state[0] ); 00318 00319 left = N, pNext = state; 00320 } 00321 00322 00323 inline MTRand::uint32 MTRand::hash( time_t t, clock_t c ) 00324 { 00325 // Get a uint32 from t and c 00326 // Better than uint32(x) in case x is floating point in [0,1] 00327 // Based on code by Lawrence Kirby (fred@genesis.demon.co.uk) 00328 00329 static uint32 differ = 0; // guarantee time-based seeds will change 00330 00331 uint32 h1 = 0; 00332 unsigned char *p = (unsigned char *) &t; 00333 for( size_t i = 0; i < sizeof(t); ++i ) 00334 { 00335 h1 *= UCHAR_MAX + 2U; 00336 h1 += p[i]; 00337 } 00338 uint32 h2 = 0; 00339 p = (unsigned char *) &c; 00340 for( size_t j = 0; j < sizeof(c); ++j ) 00341 { 00342 h2 *= UCHAR_MAX + 2U; 00343 h2 += p[j]; 00344 } 00345 return ( h1 + differ++ ) ^ h2; 00346 } 00347 00348 00349 inline void MTRand::save( uint32* saveArray ) const 00350 { 00351 register uint32 *sa = saveArray; 00352 register const uint32 *s = state; 00353 register int i = N; 00354 for( ; i--; *sa++ = *s++ ) {} 00355 *sa = left; 00356 } 00357 00358 00359 inline void MTRand::load( uint32 *const loadArray ) 00360 { 00361 register uint32 *s = state; 00362 register uint32 *la = loadArray; 00363 register int i = N; 00364 for( ; i--; *s++ = *la++ ) {} 00365 left = *la; 00366 pNext = &state[N-left]; 00367 } 00368 00369 00370 inline std::ostream& operator<<( std::ostream& os, const MTRand& mtrand ) 00371 { 00372 register const MTRand::uint32 *s = mtrand.state; 00373 register int i = mtrand.N; 00374 for( ; i--; os << *s++ << "\t" ) {} 00375 return os << mtrand.left; 00376 } 00377 00378 00379 inline std::istream& operator>>( std::istream& is, MTRand& mtrand ) 00380 { 00381 register MTRand::uint32 *s = mtrand.state; 00382 register int i = mtrand.N; 00383 for( ; i--; is >> *s++ ) {} 00384 is >> mtrand.left; 00385 mtrand.pNext = &mtrand.state[mtrand.N-mtrand.left]; 00386 return is; 00387 } 00388 00389 #endif // MERSENNETWISTER_H 00390 00391 // Change log: 00392 // 00393 // v0.1 - First release on 15 May 2000 00394 // - Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus 00395 // - Translated from C to C++ 00396 // - Made completely ANSI compliant 00397 // - Designed convenient interface for initialization, seeding, and 00398 // obtaining numbers in default or user-defined ranges 00399 // - Added automatic seeding from /dev/urandom or time() and clock() 00400 // - Provided functions for saving and loading generator state 00401 // 00402 // v0.2 - Fixed bug which reloaded generator one step too late 00403 // 00404 // v0.3 - Switched to clearer, faster reload() code from Matthew Bellew 00405 // 00406 // v0.4 - Removed trailing newline in saved generator format to be consistent 00407 // with output format of built-in types 00408 // 00409 // v0.5 - Improved portability by replacing static const int's with enum's and 00410 // clarifying return values in seed(); suggested by Eric Heimburg 00411 // - Removed MAXINT constant; use 0xffffffffUL instead 00412 // 00413 // v0.6 - Eliminated seed overflow when uint32 is larger than 32 bits 00414 // - Changed integer [0,n] generator to give better uniformity 00415 // 00416 // v0.7 - Fixed operator precedence ambiguity in reload() 00417 // - Added access for real numbers in (0,1) and (0,n) 00418 // 00419 // v0.8 - Included time.h header to properly support time_t and clock_t 00420 // 00421 // v1.0 - Revised seeding to match 26 Jan 2002 update of Nishimura and Matsumoto 00422 // - Allowed for seeding with arrays of any length 00423 // - Added access for real numbers in [0,1) with 53-bit resolution 00424 // - Added access for real numbers from normal (Gaussian) distributions 00425 // - Increased overall speed by optimizing twist() 00426 // - Doubled speed of integer [0,n] generation 00427 // - Fixed out-of-range number generation on 64-bit machines 00428 // - Improved portability by substituting literal constants for long enum's 00429 // - Changed license from GNU LGPL to BSD