Blender V2.61 - r43446

MERSENNETWISTER.h

Go to the documentation of this file.
00001 
00004 // MersenneTwister.h
00005 // Mersenne Twister random number generator -- a C++ class MTRand
00006 // Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus
00007 // Richard J. Wagner  v1.0  15 May 2003  rjwagner@writeme.com
00008 
00009 // The Mersenne Twister is an algorithm for generating random numbers.  It
00010 // was designed with consideration of the flaws in various other generators.
00011 // The period, 2^19937-1, and the order of equidistribution, 623 dimensions,
00012 // are far greater.  The generator is also fast; it avoids multiplication and
00013 // division, and it benefits from caches and pipelines.  For more information
00014 // see the inventors' web page at http://www.math.keio.ac.jp/~matumoto/emt.html
00015 
00016 // Reference
00017 // M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-Dimensionally
00018 // Equidistributed Uniform Pseudo-Random Number Generator", ACM Transactions on
00019 // Modeling and Computer Simulation, Vol. 8, No. 1, January 1998, pp 3-30.
00020 
00021 // Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
00022 // Copyright (C) 2000 - 2003, Richard J. Wagner
00023 // All rights reserved.                          
00024 //
00025 // Redistribution and use in source and binary forms, with or without
00026 // modification, are permitted provided that the following conditions
00027 // are met:
00028 //
00029 //   1. Redistributions of source code must retain the above copyright
00030 //      notice, this list of conditions and the following disclaimer.
00031 //
00032 //   2. Redistributions in binary form must reproduce the above copyright
00033 //      notice, this list of conditions and the following disclaimer in the
00034 //      documentation and/or other materials provided with the distribution.
00035 //
00036 //   3. The names of its contributors may not be used to endorse or promote 
00037 //      products derived from this software without specific prior written 
00038 //      permission.
00039 //
00040 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00041 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00042 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
00043 // A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
00044 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
00045 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
00046 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
00047 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
00048 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
00049 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
00050 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00051 
00052 // The original code included the following notice:
00053 //
00054 //     When you use this, send an email to: matumoto@math.keio.ac.jp
00055 //     with an appropriate reference to your work.
00056 //
00057 // It would be nice to CC: rjwagner@writeme.com and Cokus@math.washington.edu
00058 // when you write.
00059 
00060 #ifndef MERSENNETWISTER_H
00061 #define MERSENNETWISTER_H
00062 
00063 // Not thread safe (unless auto-initialization is avoided and each thread has
00064 // its own MTRand object)
00065 
00066 #include <iostream>
00067 #include <limits.h>
00068 #include <stdio.h>
00069 #include <time.h>
00070 #include <math.h>
00071 
00072 class MTRand {
00073 // Data
00074 public:
00075     typedef unsigned long uint32;  // unsigned integer type, at least 32 bits
00076     
00077     enum { N = 624 };       // length of state vector
00078     enum { SAVE = N + 1 };  // length of array for save()
00079 
00080 protected:
00081     enum { 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 = 1.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) + 1) & 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     register 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 (magnus@smartelectronix.com)
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     register int i = 1;
00236     register uint32 j = 0;
00237     register 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 deterministically to produce reproducible runs
00265   seed(123456);
00266   
00267   /*
00268     // Seed the generator with an array from /dev/urandom if available
00269     // Otherwise use a hash of time() and clock() values
00270     
00271     // First try getting an array from /dev/urandom
00272     FILE* urandom = fopen( "/dev/urandom", "rb" );
00273     if( urandom )
00274     {
00275         uint32 bigSeed[N];
00276         register uint32 *s = bigSeed;
00277         register int i = N;
00278         register bool success = true;
00279         while( success && i-- )
00280             success = fread( s++, sizeof(uint32), 1, urandom );
00281         fclose(urandom);
00282         if( success ) { seed( bigSeed, N );  return; }
00283     }
00284     
00285     // Was not successful, so use time() and clock() instead
00286     seed( hash( time(NULL), clock() ) );
00287   */
00288 }
00289 
00290 
00291 inline void MTRand::initialize( const uint32 seed )
00292 {
00293     // Initialize generator state with seed
00294     // See Knuth TAOCP Vol 2, 3rd Ed, p.106 for multiplier.
00295     // In previous versions, most significant bits (MSBs) of the seed affect
00296     // only MSBs of the state array.  Modified 9 Jan 2002 by Makoto Matsumoto.
00297     register uint32 *s = state;
00298     register uint32 *r = state;
00299     register int i = 1;
00300     *s++ = seed & 0xffffffffUL;
00301     for( ; i < N; ++i )
00302     {
00303         *s++ = ( 1812433253UL * ( *r ^ (*r >> 30) ) + i ) & 0xffffffffUL;
00304         r++;
00305     }
00306 }
00307 
00308 
00309 inline void MTRand::reload()
00310 {
00311     // Generate N new values in state
00312     // Made clearer and faster by Matthew Bellew (matthew.bellew@home.com)
00313     register uint32 *p = state;
00314     register int i;
00315     for( i = N - M; i--; ++p )
00316         *p = twist( p[M], p[0], p[1] );
00317     for( i = M; --i; ++p )
00318         *p = twist( p[M-N], p[0], p[1] );
00319     *p = twist( p[M-N], p[0], state[0] );
00320 
00321     left = N, pNext = state;
00322 }
00323 
00324 
00325 inline MTRand::uint32 MTRand::hash( time_t t, clock_t c )
00326 {
00327     // Get a uint32 from t and c
00328     // Better than uint32(x) in case x is floating point in [0,1]
00329     // Based on code by Lawrence Kirby (fred@genesis.demon.co.uk)
00330 
00331     static uint32 differ = 0;  // guarantee time-based seeds will change
00332 
00333     uint32 h1 = 0;
00334     unsigned char *p = (unsigned char *) &t;
00335     for( size_t i = 0; i < sizeof(t); ++i )
00336     {
00337         h1 *= UCHAR_MAX + 2U;
00338         h1 += p[i];
00339     }
00340     uint32 h2 = 0;
00341     p = (unsigned char *) &c;
00342     for( size_t j = 0; j < sizeof(c); ++j )
00343     {
00344         h2 *= UCHAR_MAX + 2U;
00345         h2 += p[j];
00346     }
00347     return ( h1 + differ++ ) ^ h2;
00348 }
00349 
00350 
00351 inline void MTRand::save( uint32* saveArray ) const
00352 {
00353     register uint32 *sa = saveArray;
00354     register const uint32 *s = state;
00355     register int i = N;
00356     for( ; i--; *sa++ = *s++ ) {}
00357     *sa = left;
00358 }
00359 
00360 
00361 inline void MTRand::load( uint32 *const loadArray )
00362 {
00363     register uint32 *s = state;
00364     register uint32 *la = loadArray;
00365     register int i = N;
00366     for( ; i--; *s++ = *la++ ) {}
00367     left = *la;
00368     pNext = &state[N-left];
00369 }
00370 
00371 
00372 inline std::ostream& operator<<( std::ostream& os, const MTRand& mtrand )
00373 {
00374     register const MTRand::uint32 *s = mtrand.state;
00375     register int i = mtrand.N;
00376     for( ; i--; os << *s++ << "\t" ) {}
00377     return os << mtrand.left;
00378 }
00379 
00380 
00381 inline std::istream& operator>>( std::istream& is, MTRand& mtrand )
00382 {
00383     register MTRand::uint32 *s = mtrand.state;
00384     register int i = mtrand.N;
00385     for( ; i--; is >> *s++ ) {}
00386     is >> mtrand.left;
00387     mtrand.pNext = &mtrand.state[mtrand.N-mtrand.left];
00388     return is;
00389 }
00390 
00391 #endif  // MERSENNETWISTER_H
00392 
00393 // Change log:
00394 //
00395 // v0.1 - First release on 15 May 2000
00396 //      - Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus
00397 //      - Translated from C to C++
00398 //      - Made completely ANSI compliant
00399 //      - Designed convenient interface for initialization, seeding, and
00400 //        obtaining numbers in default or user-defined ranges
00401 //      - Added automatic seeding from /dev/urandom or time() and clock()
00402 //      - Provided functions for saving and loading generator state
00403 //
00404 // v0.2 - Fixed bug which reloaded generator one step too late
00405 //
00406 // v0.3 - Switched to clearer, faster reload() code from Matthew Bellew
00407 //
00408 // v0.4 - Removed trailing newline in saved generator format to be consistent
00409 //        with output format of built-in types
00410 //
00411 // v0.5 - Improved portability by replacing static const int's with enum's and
00412 //        clarifying return values in seed(); suggested by Eric Heimburg
00413 //      - Removed MAXINT constant; use 0xffffffffUL instead
00414 //
00415 // v0.6 - Eliminated seed overflow when uint32 is larger than 32 bits
00416 //      - Changed integer [0,n] generator to give better uniformity
00417 //
00418 // v0.7 - Fixed operator precedence ambiguity in reload()
00419 //      - Added access for real numbers in (0,1) and (0,n)
00420 //
00421 // v0.8 - Included time.h header to properly support time_t and clock_t
00422 //
00423 // v1.0 - Revised seeding to match 26 Jan 2002 update of Nishimura and Matsumoto
00424 //      - Allowed for seeding with arrays of any length
00425 //      - Added access for real numbers in [0,1) with 53-bit resolution
00426 //      - Added access for real numbers from normal (Gaussian) distributions
00427 //      - Increased overall speed by optimizing twist()
00428 //      - Doubled speed of integer [0,n] generation
00429 //      - Fixed out-of-range number generation on 64-bit machines
00430 //      - Improved portability by substituting literal constants for long enum's
00431 //      - Changed license from GNU LGPL to BSD
00432