WFMath  1.0.1
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  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 // changed the #ifndef for wfmath in case someone uses both the lib
00058 // and the identical header separately
00059 
00060 #ifndef MERSENNETWISTER_WFMATH_H
00061 #define MERSENNETWISTER_WFMATH_H
00062 
00063 // Not thread safe (unless auto-initialization is avoided and each thread has
00064 // its own MTRand object)
00065 
00066 #include <iosfwd>
00067 #include <climits>
00068 #include <cmath>
00069 
00070 // namespace safety for inclusion in the lib
00071 
00072 namespace WFMath {
00073 
00074 class MTRand {
00075 // Data
00076 public:
00077         typedef unsigned long uint32;  // unsigned integer type, at least 32 bits
00078         
00079         static const uint32 N = 624;       // length of state vector
00080         static const uint32 SAVE = N + 1;  // length of array for save()
00081 
00082 protected:
00083         static const uint32 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         template<typename FloatT>
00102         FloatT rand();                          // real number in [0,1]
00103         float randf();                          // real number in [0,1]
00104         float randf( const float& n );          // real number in [0,n]
00105         double rand();                          // real number in [0,1]
00106         double rand( const double& n );         // real number in [0,n]
00107         double randExc();                       // real number in [0,1)
00108         double randExc( const double& n );      // real number in [0,n)
00109         double randDblExc();                    // real number in (0,1)
00110         double randDblExc( const double& n );   // real number in (0,n)
00111         uint32 randInt();                       // integer in [0,2^32-1]
00112         uint32 randInt( const uint32& n );      // integer in [0,n] for n < 2^32
00113         double operator()() { return rand(); }  // same as rand()
00114         
00115         // Access to 53-bit random numbers (capacity of IEEE double precision)
00116         double rand53();  // real number in [0,1)
00117         
00118         // Access to nonuniform random number distributions
00119         double randNorm( const double& mean = 0.0, const double& variance = 0.0 );
00120         
00121         // Re-seeding functions with same behavior as initializers
00122         void seed( const uint32 oneSeed );
00123         void seed( uint32 *const bigSeed, const uint32 seedLength = N );
00124         void seed();
00125         
00126         // Saving and loading generator state
00127         void save( uint32* saveArray ) const;  // to array of size SAVE
00128         void load( uint32 *const loadArray );  // from such array
00129         friend std::ostream& operator<<( std::ostream& os, const MTRand& mtrand );
00130         friend std::istream& operator>>( std::istream& is, MTRand& mtrand );
00131 
00132         static MTRand instance;
00133 
00134 protected:
00135         void initialize( const uint32 oneSeed );
00136         void reload();
00137         uint32 hiBit( const uint32& u ) const { return u & 0x80000000UL; }
00138         uint32 loBit( const uint32& u ) const { return u & 0x00000001UL; }
00139         uint32 loBits( const uint32& u ) const { return u & 0x7fffffffUL; }
00140         uint32 mixBits( const uint32& u, const uint32& v ) const
00141                 { return hiBit(u) | loBits(v); }
00142         uint32 twist( const uint32& m, const uint32& s0, const uint32& s1 ) const
00143                 { return m ^ (mixBits(s0,s1)>>1) ^ (-loBit(s1) & 0x9908b0dfUL); }
00144 };
00145 
00146 
00147 inline MTRand::MTRand( const uint32& oneSeed ) : pNext(0), left(0)
00148         { seed(oneSeed); }
00149 
00150 inline MTRand::MTRand( uint32 *const bigSeed, const uint32 seedLength ) : pNext(0), left(0)
00151         { seed(bigSeed,seedLength); }
00152 
00153 inline MTRand::MTRand() : pNext(0), left(0)
00154         { seed(); }
00155 
00156 template<>
00157 inline float MTRand::rand<float>()
00158         { return float(randInt()) * (1.0f/4294967295.0f); }
00159 
00160 template<>
00161 inline double MTRand::rand<double>()
00162         { return double(randInt()) * (1.0/4294967295.0); }
00163 
00164 inline float MTRand::randf()
00165         { return float(randInt()) * (1.0f/4294967295.0f); }
00166 
00167 inline float MTRand::randf( const float& n )
00168         { return randf() * n; }
00169 
00170 inline double MTRand::rand()
00171         { return double(randInt()) * (1.0/4294967295.0); }
00172 
00173 inline double MTRand::rand( const double& n )
00174         { return rand() * n; }
00175 
00176 inline double MTRand::randExc()
00177         { return double(randInt()) * (1.0/4294967296.0); }
00178 
00179 inline double MTRand::randExc( const double& n )
00180         { return randExc() * n; }
00181 
00182 inline double MTRand::randDblExc()
00183         { return ( double(randInt()) + 0.5 ) * (1.0/4294967296.0); }
00184 
00185 inline double MTRand::randDblExc( const double& n )
00186         { return randDblExc() * n; }
00187 
00188 inline double MTRand::rand53()
00189 {
00190         uint32 a = randInt() >> 5, b = randInt() >> 6;
00191         return ( a * 67108864.0 + b ) * (1.0/9007199254740992.0);  // by Isaku Wada
00192 }
00193 
00194 inline double MTRand::randNorm( const double& mean, const double& variance )
00195 {
00196         // Return a real number from a normal (Gaussian) distribution with given
00197         // mean and variance by Box-Muller method
00198         double r = std::sqrt( -2.0 * std::log( 1.0-randDblExc()) ) * variance;
00199         double phi = 2.0 * 3.14159265358979323846264338328 * randExc();
00200         return mean + r * std::cos(phi);
00201 }
00202 
00203 inline MTRand::uint32 MTRand::randInt()
00204 {
00205         // Pull a 32-bit integer from the generator state
00206         // Every other access function simply transforms the numbers extracted here
00207         
00208         if( left == 0 ) reload();
00209         --left;
00210                 
00211         register uint32 s1;
00212         s1 = *pNext++;
00213         s1 ^= (s1 >> 11);
00214         s1 ^= (s1 <<  7) & 0x9d2c5680UL;
00215         s1 ^= (s1 << 15) & 0xefc60000UL;
00216         return ( s1 ^ (s1 >> 18) );
00217 }
00218 
00219 inline MTRand::uint32 MTRand::randInt( const uint32& n )
00220 {
00221         // Find which bits are used in n
00222         // Optimized by Magnus Jonsson (magnus@smartelectronix.com)
00223         uint32 used = n;
00224         used |= used >> 1;
00225         used |= used >> 2;
00226         used |= used >> 4;
00227         used |= used >> 8;
00228         used |= used >> 16;
00229         
00230         // Draw numbers until one is found in [0,n]
00231         uint32 i;
00232         do
00233                 i = randInt() & used;  // toss unused bits to shorten search
00234         while( i > n );
00235         return i;
00236 }
00237 
00238 
00239 inline void MTRand::seed( const uint32 oneSeed )
00240 {
00241         // Seed the generator with a simple uint32
00242         initialize(oneSeed);
00243         reload();
00244 }
00245 
00246 
00247 inline void MTRand::seed( uint32 *const bigSeed, const uint32 seedLength )
00248 {
00249         // Seed the generator with an array of uint32's
00250         // There are 2^19937-1 possible initial states.  This function allows
00251         // all of those to be accessed by providing at least 19937 bits (with a
00252         // default seed length of N = 624 uint32's).  Any bits above the lower 32
00253         // in each element are discarded.
00254         // Just call seed() if you want to get array from /dev/urandom
00255         initialize(19650218UL);
00256         register unsigned i = 1;
00257         register uint32 j = 0;
00258         register unsigned k = ( N > seedLength ? N : seedLength );
00259         for( ; k; --k )
00260         {
00261                 state[i] =
00262                         state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1664525UL );
00263                 state[i] += ( bigSeed[j] & 0xffffffffUL ) + j;
00264                 state[i] &= 0xffffffffUL;
00265                 ++i;  ++j;
00266                 if( i >= N ) { state[0] = state[N-1];  i = 1; }
00267                 if( j >= seedLength ) j = 0;
00268         }
00269         for( k = N - 1; k; --k )
00270         {
00271                 state[i] =
00272                         state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1566083941UL );
00273                 state[i] -= i;
00274                 state[i] &= 0xffffffffUL;
00275                 ++i;
00276                 if( i >= N ) { state[0] = state[N-1];  i = 1; }
00277         }
00278         state[0] = 0x80000000UL;  // MSB is 1, assuring non-zero initial array
00279         reload();
00280 }
00281 
00282 
00283 inline void MTRand::initialize( const uint32 seed )
00284 {
00285         // Initialize generator state with seed
00286         // See Knuth TAOCP Vol 2, 3rd Ed, p.106 for multiplier.
00287         // In previous versions, most significant bits (MSBs) of the seed affect
00288         // only MSBs of the state array.  Modified 9 Jan 2002 by Makoto Matsumoto.
00289         register uint32 *s = state;
00290         register uint32 *r = state;
00291         register unsigned i = 1;
00292         *s++ = seed & 0xffffffffUL;
00293         for( ; i < N; ++i )
00294         {
00295                 *s++ = ( 1812433253UL * ( *r ^ (*r >> 30) ) + i ) & 0xffffffffUL;
00296                 r++;
00297         }
00298 }
00299 
00300 
00301 inline void MTRand::reload()
00302 {
00303         // Generate N new values in state
00304         // Made clearer and faster by Matthew Bellew (matthew.bellew@home.com)
00305         register uint32 *p = state;
00306         register int i;
00307         for( i = N - M; i--; ++p )
00308                 *p = twist( p[M], p[0], p[1] );
00309         for( i = M; --i; ++p )
00310                 *p = twist( p[M-N], p[0], p[1] );
00311         *p = twist( p[M-N], p[0], state[0] );
00312 
00313         left = N, pNext = state;
00314 }
00315 
00316 
00317 
00318 inline void MTRand::save( uint32* saveArray ) const
00319 {
00320         register uint32 *sa = saveArray;
00321         register const uint32 *s = state;
00322         register int i = N;
00323         for( ; i--; *sa++ = *s++ ) {}
00324         *sa = left;
00325 }
00326 
00327 
00328 inline void MTRand::load( uint32 *const loadArray )
00329 {
00330         register uint32 *s = state;
00331         register uint32 *la = loadArray;
00332         register int i = N;
00333         for( ; i--; *s++ = *la++ ) {}
00334         left = *la;
00335         pNext = &state[N-left];
00336 }
00337 
00338 
00339 } // namespace
00340 
00341 #endif  // MERSENNETWISTER_H
00342 
00343 // Change log:
00344 //
00345 // v0.1 - First release on 15 May 2000
00346 //      - Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus
00347 //      - Translated from C to C++
00348 //      - Made completely ANSI compliant
00349 //      - Designed convenient interface for initialization, seeding, and
00350 //        obtaining numbers in default or user-defined ranges
00351 //      - Added automatic seeding from /dev/urandom or time() and clock()
00352 //      - Provided functions for saving and loading generator state
00353 //
00354 // v0.2 - Fixed bug which reloaded generator one step too late
00355 //
00356 // v0.3 - Switched to clearer, faster reload() code from Matthew Bellew
00357 //
00358 // v0.4 - Removed trailing newline in saved generator format to be consistent
00359 //        with output format of built-in types
00360 //
00361 // v0.5 - Improved portability by replacing static const int's with enum's and
00362 //        clarifying return values in seed(); suggested by Eric Heimburg
00363 //      - Removed MAXINT constant; use 0xffffffffUL instead
00364 //
00365 // v0.6 - Eliminated seed overflow when uint32 is larger than 32 bits
00366 //      - Changed integer [0,n] generator to give better uniformity
00367 //
00368 // v0.7 - Fixed operator precedence ambiguity in reload()
00369 //      - Added access for real numbers in (0,1) and (0,n)
00370 //
00371 // v0.8 - Included time.h header to properly support time_t and clock_t
00372 //
00373 // v1.0 - Revised seeding to match 26 Jan 2002 update of Nishimura and Matsumoto
00374 //      - Allowed for seeding with arrays of any length
00375 //      - Added access for real numbers in [0,1) with 53-bit resolution
00376 //      - Added access for real numbers from normal (Gaussian) distributions
00377 //      - Increased overall speed by optimizing twist()
00378 //      - Doubled speed of integer [0,n] generation
00379 //      - Fixed out-of-range number generation on 64-bit machines
00380 //      - Improved portability by substituting literal constants for long enum's
00381 //      - Changed license from GNU LGPL to BSD