mersennetwister.h

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  [email protected]
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: [email protected]
00052 //     with an appropriate reference to your work.
00053 //
00054 // It would be nice to CC: [email protected] and [email protected]
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 #include <iostream>
00064 #include <limits.h>
00065 #include <stdio.h>
00066 #include <time.h>
00067 #include <math.h>
00068 
00069 NAMESPACE_BEGIN
00070 
00071 class MTRand {
00072 // Data
00073 public:
00074     typedef unsigned long uint32;  // unsigned integer type, at least 32 bits
00075 
00076     enum Dummy1 { N = 624 };       // length of state vector
00077     enum Dummy2 { SAVE = N + 1 };  // length of array for save()
00078     // Note: DummyX names needed by buggy gcc 4.0.1 on OS/X (Andras)
00079 
00080 protected:
00081     enum Dummy3 { M = 397 };  // period parameter
00082 
00083     uint32 state[N];   // internal state
00084     uint32 *pNext;     // next value to get from state
00085     int left;          // number of values left before reload needed
00086 
00087 
00088 //Methods
00089 public:
00090     MTRand( const uint32& oneSeed );  // initialize with a simple uint32
00091     MTRand( uint32 *const bigSeed, uint32 const seedLength = N );  // or an array
00092     MTRand();  // auto-initialize with /dev/urandom or time() and clock()
00093 
00094     // Do NOT use for CRYPTOGRAPHY without securely hashing several returned
00095     // values together, otherwise the generator state can be learned after
00096     // reading 624 consecutive values.
00097 
00098     // Access to 32-bit random numbers
00099     double rand();                          // real number in [0,1]
00100     double rand( const double& n );         // real number in [0,n]
00101     double randExc();                       // real number in [0,1)
00102     double randExc( const double& n );      // real number in [0,n)
00103     double randDblExc();                    // real number in (0,1)
00104     double randDblExc( const double& n );   // real number in (0,n)
00105     uint32 randInt();                       // integer in [0,2^32-1]
00106     uint32 randInt( const uint32& n );      // integer in [0,n] for n < 2^32
00107     double operator()() { return rand(); }  // same as rand()
00108 
00109     // Access to 53-bit random numbers (capacity of IEEE double precision)
00110     double rand53();  // real number in [0,1)
00111 
00112     // Access to nonuniform random number distributions
00113     double randNorm( const double& mean = 0.0, const double& variance = 0.0 );
00114 
00115     // Re-seeding functions with same behavior as initializers
00116     void seed( const uint32 oneSeed );
00117     void seed( uint32 *const bigSeed, const uint32 seedLength = N );
00118     void seed();
00119 
00120     // Saving and loading generator state
00121     void save( uint32* saveArray ) const;  // to array of size SAVE
00122     void load( uint32 *const loadArray );  // from such array
00123     friend std::ostream& operator<<( std::ostream& os, const MTRand& mtrand );
00124     friend std::istream& operator>>( std::istream& is, MTRand& mtrand );
00125 
00126 protected:
00127     void initialize( const uint32 oneSeed );
00128     void reload();
00129     uint32 hiBit( const uint32& u ) const { return u & 0x80000000UL; }
00130     uint32 loBit( const uint32& u ) const { return u & 0x00000001UL; }
00131     uint32 loBits( const uint32& u ) const { return u & 0x7fffffffUL; }
00132     uint32 mixBits( const uint32& u, const uint32& v ) const
00133         { return hiBit(u) | loBits(v); }
00134     uint32 twist( const uint32& m, const uint32& s0, const uint32& s1 ) const
00135         { return m ^ (mixBits(s0,s1)>>1) ^ (-loBit(s1) & 0x9908b0dfUL); }
00136     static uint32 hash( time_t t, clock_t c );
00137 };
00138 
00139 
00140 inline MTRand::MTRand( const uint32& oneSeed )
00141     { seed(oneSeed); }
00142 
00143 inline MTRand::MTRand( uint32 *const bigSeed, const uint32 seedLength )
00144     { seed(bigSeed,seedLength); }
00145 
00146 inline MTRand::MTRand()
00147     { seed(); }
00148 
00149 inline double MTRand::rand()
00150     { return double(randInt()) * (1.0/4294967295.0); }
00151 
00152 inline double MTRand::rand( const double& n )
00153     { return rand() * n; }
00154 
00155 inline double MTRand::randExc()
00156     { return double(randInt()) * (1.0/4294967296.0); }
00157 
00158 inline double MTRand::randExc( const double& n )
00159     { return randExc() * n; }
00160 
00161 inline double MTRand::randDblExc()
00162     { return ( double(randInt()) + 0.5 ) * (1.0/4294967296.0); }
00163 
00164 inline double MTRand::randDblExc( const double& n )
00165     { return randDblExc() * n; }
00166 
00167 inline double MTRand::rand53()
00168 {
00169     uint32 a = randInt() >> 5, b = randInt() >> 6;
00170     return ( a * 67108864.0 + b ) * (1.0/9007199254740992.0);  // by Isaku Wada
00171 }
00172 
00173 inline double MTRand::randNorm( const double& mean, const double& variance )
00174 {
00175     // Return a real number from a normal (Gaussian) distribution with given
00176     // mean and variance by Box-Muller method
00177     double r = sqrt( -2.0 * log( 1.0-randDblExc()) ) * variance;
00178     double phi = 2.0 * 3.14159265358979323846264338328 * randExc();
00179     return mean + r * cos(phi);
00180 }
00181 
00182 inline MTRand::uint32 MTRand::randInt()
00183 {
00184     // Pull a 32-bit integer from the generator state
00185     // Every other access function simply transforms the numbers extracted here
00186 
00187     if( left == 0 ) reload();
00188     --left;
00189 
00190     uint32 s1;
00191     s1 = *pNext++;
00192     s1 ^= (s1 >> 11);
00193     s1 ^= (s1 <<  7) & 0x9d2c5680UL;
00194     s1 ^= (s1 << 15) & 0xefc60000UL;
00195     return ( s1 ^ (s1 >> 18) );
00196 }
00197 
00198 inline MTRand::uint32 MTRand::randInt( const uint32& n )
00199 {
00200     // Find which bits are used in n
00201     // Optimized by Magnus Jonsson ([email protected])
00202     uint32 used = n;
00203     used |= used >> 1;
00204     used |= used >> 2;
00205     used |= used >> 4;
00206     used |= used >> 8;
00207     used |= used >> 16;
00208 
00209     // Draw numbers until one is found in [0,n]
00210     uint32 i;
00211     do
00212         i = randInt() & used;  // toss unused bits to shorten search
00213     while( i > n );
00214     return i;
00215 }
00216 
00217 
00218 inline void MTRand::seed( const uint32 oneSeed )
00219 {
00220     // Seed the generator with a simple uint32
00221     initialize(oneSeed);
00222     reload();
00223 }
00224 
00225 
00226 inline void MTRand::seed( uint32 *const bigSeed, const uint32 seedLength )
00227 {
00228     // Seed the generator with an array of uint32's
00229     // There are 2^19937-1 possible initial states.  This function allows
00230     // all of those to be accessed by providing at least 19937 bits (with a
00231     // default seed length of N = 624 uint32's).  Any bits above the lower 32
00232     // in each element are discarded.
00233     // Just call seed() if you want to get array from /dev/urandom
00234     initialize(19650218UL);
00235     int i = 1;
00236     uint32 j = 0;
00237     int k = ( N > seedLength ? N : seedLength );
00238     for( ; k; --k )
00239     {
00240         state[i] =
00241             state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1664525UL );
00242         state[i] += ( bigSeed[j] & 0xffffffffUL ) + j;
00243         state[i] &= 0xffffffffUL;
00244         ++i;  ++j;
00245         if( i >= N ) { state[0] = state[N-1];  i = 1; }
00246         if( j >= seedLength ) j = 0;
00247     }
00248     for( k = N - 1; k; --k )
00249     {
00250         state[i] =
00251             state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1566083941UL );
00252         state[i] -= i;
00253         state[i] &= 0xffffffffUL;
00254         ++i;
00255         if( i >= N ) { state[0] = state[N-1];  i = 1; }
00256     }
00257     state[0] = 0x80000000UL;  // MSB is 1, assuring non-zero initial array
00258     reload();
00259 }
00260 
00261 
00262 inline void MTRand::seed()
00263 {
00264     // Seed the generator with an array from /dev/urandom if available
00265     // Otherwise use a hash of time() and clock() values
00266 
00267     // First try getting an array from /dev/urandom
00268     FILE* urandom = fopen( "/dev/urandom", "rb" );
00269     if( urandom )
00270     {
00271         uint32 bigSeed[N];
00272         uint32 *s = bigSeed;
00273         int i = N;
00274         bool success = true;
00275         while( success && i-- )
00276             success = fread( s++, sizeof(uint32), 1, urandom );
00277         fclose(urandom);
00278         if( success ) { seed( bigSeed, N );  return; }
00279     }
00280 
00281     // Was not successful, so use time() and clock() instead
00282     seed( hash( time(NULL), clock() ) );
00283 }
00284 
00285 
00286 inline void MTRand::initialize( const uint32 seed )
00287 {
00288     // Initialize generator state with seed
00289     // See Knuth TAOCP Vol 2, 3rd Ed, p.106 for multiplier.
00290     // In previous versions, most significant bits (MSBs) of the seed affect
00291     // only MSBs of the state array.  Modified 9 Jan 2002 by Makoto Matsumoto.
00292     uint32 *s = state;
00293     uint32 *r = state;
00294     int i = 1;
00295     *s++ = seed & 0xffffffffUL;
00296     for( ; i < N; ++i )
00297     {
00298         *s++ = ( 1812433253UL * ( *r ^ (*r >> 30) ) + i ) & 0xffffffffUL;
00299         r++;
00300     }
00301 }
00302 
00303 
00304 inline void MTRand::reload()
00305 {
00306     // Generate N new values in state
00307     // Made clearer and faster by Matthew Bellew ([email protected])
00308     uint32 *p = state;
00309     int i;
00310     for( i = N - M; i--; ++p )
00311         *p = twist( p[M], p[0], p[1] );
00312     for( i = M; --i; ++p )
00313         *p = twist( p[M-N], p[0], p[1] );
00314     *p = twist( p[M-N], p[0], state[0] );
00315 
00316     left = N, pNext = state;
00317 }
00318 
00319 
00320 inline MTRand::uint32 MTRand::hash( time_t t, clock_t c )
00321 {
00322     // Get a uint32 from t and c
00323     // Better than uint32(x) in case x is floating point in [0,1]
00324     // Based on code by Lawrence Kirby ([email protected])
00325 
00326     static uint32 differ = 0;  // guarantee time-based seeds will change
00327 
00328     uint32 h1 = 0;
00329     unsigned char *p = (unsigned char *) &t;
00330     for( size_t i = 0; i < sizeof(t); ++i )
00331     {
00332         h1 *= UCHAR_MAX + 2U;
00333         h1 += p[i];
00334     }
00335     uint32 h2 = 0;
00336     p = (unsigned char *) &c;
00337     for( size_t j = 0; j < sizeof(c); ++j )
00338     {
00339         h2 *= UCHAR_MAX + 2U;
00340         h2 += p[j];
00341     }
00342     return ( h1 + differ++ ) ^ h2;
00343 }
00344 
00345 
00346 inline void MTRand::save( uint32* saveArray ) const
00347 {
00348     uint32 *sa = saveArray;
00349     const uint32 *s = state;
00350     int i = N;
00351     for( ; i--; *sa++ = *s++ ) {}
00352     *sa = left;
00353 }
00354 
00355 
00356 inline void MTRand::load( uint32 *const loadArray )
00357 {
00358     uint32 *s = state;
00359     uint32 *la = loadArray;
00360     int i = N;
00361     for( ; i--; *s++ = *la++ ) {}
00362     left = *la;
00363     pNext = &state[N-left];
00364 }
00365 
00366 
00367 inline std::ostream& operator<<( std::ostream& os, const MTRand& mtrand )
00368 {
00369     const MTRand::uint32 *s = mtrand.state;
00370     int i = mtrand.N;
00371     for( ; i--; os << *s++ << "\t" ) {}
00372     return os << mtrand.left;
00373 }
00374 
00375 
00376 inline std::istream& operator>>( std::istream& is, MTRand& mtrand )
00377 {
00378     MTRand::uint32 *s = mtrand.state;
00379     int i = mtrand.N;
00380     for( ; i--; is >> *s++ ) {}
00381     is >> mtrand.left;
00382     mtrand.pNext = &mtrand.state[mtrand.N-mtrand.left];
00383     return is;
00384 }
00385 
00386 NAMESPACE_END
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
Generated on Tue Dec 2 11:16:27 2014 for OMNeT++ Simulation Library by  doxygen 1.6.3