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