Guest User

Untitled

a guest
Dec 25th, 2011
40
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // MersenneTwister.h
  2. // Mersenne Twister random number generator -- a C++ class MTRand
  3. // Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus
  4. // Richard J. Wagner  v1.1  28 September 2009  wagnerr@umich.edu
  5.  
  6. // The Mersenne Twister is an algorithm for generating random numbers.  It
  7. // was designed with consideration of the flaws in various other generators.
  8. // The period, 2^19937-1, and the order of equidistribution, 623 dimensions,
  9. // are far greater.  The generator is also fast; it avoids multiplication and
  10. // division, and it benefits from caches and pipelines.  For more information
  11. // see the inventors' web page at
  12. // http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
  13.  
  14. // Reference
  15. // M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-Dimensionally
  16. // Equidistributed Uniform Pseudo-Random Number Generator", ACM Transactions on
  17. // Modeling and Computer Simulation, Vol. 8, No. 1, January 1998, pp 3-30.
  18.  
  19. // Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
  20. // Copyright (C) 2000 - 2009, Richard J. Wagner
  21. // All rights reserved.
  22. //
  23. // Redistribution and use in source and binary forms, with or without
  24. // modification, are permitted provided that the following conditions
  25. // are met:
  26. //
  27. //   1. Redistributions of source code must retain the above copyright
  28. //      notice, this list of conditions and the following disclaimer.
  29. //
  30. //   2. Redistributions in binary form must reproduce the above copyright
  31. //      notice, this list of conditions and the following disclaimer in the
  32. //      documentation and/or other materials provided with the distribution.
  33. //
  34. //   3. The names of its contributors may not be used to endorse or promote
  35. //      products derived from this software without specific prior written
  36. //      permission.
  37. //
  38. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  39. // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  40. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  41. // ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  42. // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  43. // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  44. // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  45. // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  46. // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  47. // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  48. // POSSIBILITY OF SUCH DAMAGE.
  49.  
  50. #ifndef MERSENNETWISTER_H
  51. #define MERSENNETWISTER_H
  52.  
  53. // Not thread safe (unless auto-initialization is avoided and each thread has
  54. // its own MTRand object)
  55.  
  56. #include <iostream>
  57. #include <climits>
  58. #include <cstdio>
  59. #include <ctime>
  60. #include <cmath>
  61. #pragma warning(disable:4996;disable:4800)
  62.  
  63. class MTRand {
  64. // Data
  65. public:
  66.     typedef unsigned long uint32;  // unsigned integer type, at least 32 bits
  67.    
  68.     enum { N = 624 };       // length of state vector
  69.     enum { SAVE = N + 1 };  // length of array for save()
  70.  
  71. protected:
  72.     enum { M = 397 };  // period parameter
  73.    
  74.     uint32 state[N];   // internal state
  75.     uint32 *pNext;     // next value to get from state
  76.     int left;          // number of values left before reload needed
  77.  
  78. // Methods
  79. public:
  80.     MTRand( const uint32 oneSeed );  // initialize with a simple uint32
  81.     MTRand( uint32 *const bigSeed, uint32 const seedLength = N );  // or array
  82.     MTRand();  // auto-initialize with /dev/urandom or time() and clock()
  83.     MTRand( const MTRand& o );  // copy
  84.    
  85.     // Do NOT use for CRYPTOGRAPHY without securely hashing several returned
  86.     // values together, otherwise the generator state can be learned after
  87.     // reading 624 consecutive values.
  88.    
  89.     // Access to 32-bit random numbers
  90.     uint32 randInt();                     // integer in [0,2^32-1]
  91.     uint32 randInt( const uint32 n );     // integer in [0,n] for n < 2^32
  92.     double rand();                        // real number in [0,1]
  93.     double rand( const double n );        // real number in [0,n]
  94.     double randExc();                     // real number in [0,1)
  95.     double randExc( const double n );     // real number in [0,n)
  96.     double randDblExc();                  // real number in (0,1)
  97.     double randDblExc( const double n );  // real number in (0,n)
  98.     double operator()();                  // same as rand()
  99.    
  100.     // Access to 53-bit random numbers (capacity of IEEE double precision)
  101.     double rand53();  // real number in [0,1)
  102.    
  103.     // Access to nonuniform random number distributions
  104.     double randNorm( const double mean = 0.0, const double stddev = 1.0 );
  105.    
  106.     // Re-seeding functions with same behavior as initializers
  107.     void seed( const uint32 oneSeed );
  108.     void seed( uint32 *const bigSeed, const uint32 seedLength = N );
  109.     void seed();
  110.    
  111.     // Saving and loading generator state
  112.     void save( uint32* saveArray ) const;  // to array of size SAVE
  113.     void load( uint32 *const loadArray );  // from such array
  114.     friend std::ostream& operator<<( std::ostream& os, const MTRand& mtrand );
  115.     friend std::istream& operator>>( std::istream& is, MTRand& mtrand );
  116.     MTRand& operator=( const MTRand& o );
  117.  
  118. protected:
  119.     void initialize( const uint32 oneSeed );
  120.     void reload();
  121.     uint32 hiBit( const uint32 u ) const { return u & 0x80000000UL; }
  122.     uint32 loBit( const uint32 u ) const { return u & 0x00000001UL; }
  123.     uint32 loBits( const uint32 u ) const { return u & 0x7fffffffUL; }
  124.     uint32 mixBits( const uint32 u, const uint32 v ) const
  125.         { return hiBit(u) | loBits(v); }
  126.     uint32 magic( const uint32 u ) const
  127.         { return loBit(u) ? 0x9908b0dfUL : 0x0UL; }
  128.     uint32 twist( const uint32 m, const uint32 s0, const uint32 s1 ) const
  129.         { return m ^ (mixBits(s0,s1)>>1) ^ magic(s1); }
  130.     static uint32 hash( time_t t, clock_t c );
  131. };
  132.  
  133. // Functions are defined in order of usage to assist inlining
  134.  
  135. inline MTRand::uint32 MTRand::hash( time_t t, clock_t c )
  136. {
  137.     // Get a uint32 from t and c
  138.     // Better than uint32(x) in case x is floating point in [0,1]
  139.     // Based on code by Lawrence Kirby (fred@genesis.demon.co.uk)
  140.    
  141.     static uint32 differ = 0;  // guarantee time-based seeds will change
  142.    
  143.     uint32 h1 = 0;
  144.     unsigned char *p = (unsigned char *) &t;
  145.     for( size_t i = 0; i < sizeof(t); ++i )
  146.     {
  147.         h1 *= UCHAR_MAX + 2U;
  148.         h1 += p[i];
  149.     }
  150.     uint32 h2 = 0;
  151.     p = (unsigned char *) &c;
  152.     for( size_t j = 0; j < sizeof(c); ++j )
  153.     {
  154.         h2 *= UCHAR_MAX + 2U;
  155.         h2 += p[j];
  156.     }
  157.     return ( h1 + differ++ ) ^ h2;
  158. }
  159.  
  160. inline void MTRand::initialize( const uint32 seed )
  161. {
  162.     // Initialize generator state with seed
  163.     // See Knuth TAOCP Vol 2, 3rd Ed, p.106 for multiplier.
  164.     // In previous versions, most significant bits (MSBs) of the seed affect
  165.     // only MSBs of the state array.  Modified 9 Jan 2002 by Makoto Matsumoto.
  166.     register uint32 *s = state;
  167.     register uint32 *r = state;
  168.     register int i = 1;
  169.     *s++ = seed & 0xffffffffUL;
  170.     for( ; i < N; ++i )
  171.     {
  172.         *s++ = ( 1812433253UL * ( *r ^ (*r >> 30) ) + i ) & 0xffffffffUL;
  173.         r++;
  174.     }
  175. }
  176.  
  177. inline void MTRand::reload()
  178. {
  179.     // Generate N new values in state
  180.     // Made clearer and faster by Matthew Bellew (matthew.bellew@home.com)
  181.     static const int MmN = int(M) - int(N);  // in case enums are unsigned
  182.     register uint32 *p = state;
  183.     register int i;
  184.     for( i = N - M; i--; ++p )
  185.         *p = twist( p[M], p[0], p[1] );
  186.     for( i = M; --i; ++p )
  187.         *p = twist( p[MmN], p[0], p[1] );
  188.     *p = twist( p[MmN], p[0], state[0] );
  189.    
  190.     left = N, pNext = state;
  191. }
  192.  
  193. inline void MTRand::seed( const uint32 oneSeed )
  194. {
  195.     // Seed the generator with a simple uint32
  196.     initialize(oneSeed);
  197.     reload();
  198. }
  199.  
  200. inline void MTRand::seed( uint32 *const bigSeed, const uint32 seedLength )
  201. {
  202.     // Seed the generator with an array of uint32's
  203.     // There are 2^19937-1 possible initial states.  This function allows
  204.     // all of those to be accessed by providing at least 19937 bits (with a
  205.     // default seed length of N = 624 uint32's).  Any bits above the lower 32
  206.     // in each element are discarded.
  207.     // Just call seed() if you want to get array from /dev/urandom
  208.     initialize(19650218UL);
  209.     register int i = 1;
  210.     register uint32 j = 0;
  211.     register int k = ( N > seedLength ? N : seedLength );
  212.     for( ; k; --k )
  213.     {
  214.         state[i] =
  215.         state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1664525UL );
  216.         state[i] += ( bigSeed[j] & 0xffffffffUL ) + j;
  217.         state[i] &= 0xffffffffUL;
  218.         ++i;  ++j;
  219.         if( i >= N ) { state[0] = state[N-1];  i = 1; }
  220.         if( j >= seedLength ) j = 0;
  221.     }
  222.     for( k = N - 1; k; --k )
  223.     {
  224.         state[i] =
  225.         state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1566083941UL );
  226.         state[i] -= i;
  227.         state[i] &= 0xffffffffUL;
  228.         ++i;
  229.         if( i >= N ) { state[0] = state[N-1];  i = 1; }
  230.     }
  231.     state[0] = 0x80000000UL;  // MSB is 1, assuring non-zero initial array
  232.     reload();
  233. }
  234.  
  235. inline void MTRand::seed()
  236. {
  237.     // Seed the generator with an array from /dev/urandom if available
  238.     // Otherwise use a hash of time() and clock() values
  239.    
  240.     // First try getting an array from /dev/urandom
  241.     FILE* urandom = fopen( "/dev/urandom", "rb" );
  242.     if( urandom )
  243.     {
  244.         uint32 bigSeed[N];
  245.         register uint32 *s = bigSeed;
  246.         register int i = N;
  247.         register bool success = true;
  248.         while( success && i-- )
  249.             success = fread( s++, sizeof(uint32), 1, urandom );
  250.         fclose(urandom);
  251.         if( success ) { seed( bigSeed, N );  return; }
  252.     }
  253.    
  254.     // Was not successful, so use time() and clock() instead
  255.     seed( hash( time(NULL), clock() ) );
  256. }
  257.  
  258. inline MTRand::MTRand( const uint32 oneSeed )
  259.     { seed(oneSeed); }
  260.  
  261. inline MTRand::MTRand( uint32 *const bigSeed, const uint32 seedLength )
  262.     { seed(bigSeed,seedLength); }
  263.  
  264. inline MTRand::MTRand()
  265.     { seed(); }
  266.  
  267. inline MTRand::MTRand( const MTRand& o )
  268. {
  269.     register const uint32 *t = o.state;
  270.     register uint32 *s = state;
  271.     register int i = N;
  272.     for( ; i--; *s++ = *t++ ) {}
  273.     left = o.left;
  274.     pNext = &state[N-left];
  275. }
  276.  
  277. inline MTRand::uint32 MTRand::randInt()
  278. {
  279.     // Pull a 32-bit integer from the generator state
  280.     // Every other access function simply transforms the numbers extracted here
  281.    
  282.     if( left == 0 ) reload();
  283.     --left;
  284.    
  285.     register uint32 s1;
  286.     s1 = *pNext++;
  287.     s1 ^= (s1 >> 11);
  288.     s1 ^= (s1 <<  7) & 0x9d2c5680UL;
  289.     s1 ^= (s1 << 15) & 0xefc60000UL;
  290.     return ( s1 ^ (s1 >> 18) );
  291. }
  292.  
  293. inline MTRand::uint32 MTRand::randInt( const uint32 n )
  294. {
  295.     // Find which bits are used in n
  296.     // Optimized by Magnus Jonsson (magnus@smartelectronix.com)
  297.     uint32 used = n;
  298.     used |= used >> 1;
  299.     used |= used >> 2;
  300.     used |= used >> 4;
  301.     used |= used >> 8;
  302.     used |= used >> 16;
  303.    
  304.     // Draw numbers until one is found in [0,n]
  305.     uint32 i;
  306.     do
  307.         i = randInt() & used;  // toss unused bits to shorten search
  308.     while( i > n );
  309.     return i;
  310. }
  311.  
  312. inline double MTRand::rand()
  313.     { return double(randInt()) * (1.0/4294967295.0); }
  314.  
  315. inline double MTRand::rand( const double n )
  316.     { return rand() * n; }
  317.  
  318. inline double MTRand::randExc()
  319.     { return double(randInt()) * (1.0/4294967296.0); }
  320.  
  321. inline double MTRand::randExc( const double n )
  322.     { return randExc() * n; }
  323.  
  324. inline double MTRand::randDblExc()
  325.     { return ( double(randInt()) + 0.5 ) * (1.0/4294967296.0); }
  326.  
  327. inline double MTRand::randDblExc( const double n )
  328.     { return randDblExc() * n; }
  329.  
  330. inline double MTRand::rand53()
  331. {
  332.     uint32 a = randInt() >> 5, b = randInt() >> 6;
  333.     return ( a * 67108864.0 + b ) * (1.0/9007199254740992.0);  // by Isaku Wada
  334. }
  335.  
  336. inline double MTRand::randNorm( const double mean, const double stddev )
  337. {
  338.     // Return a real number from a normal (Gaussian) distribution with given
  339.     // mean and standard deviation by polar form of Box-Muller transformation
  340.     double x, y, r;
  341.     do
  342.     {
  343.         x = 2.0 * rand() - 1.0;
  344.         y = 2.0 * rand() - 1.0;
  345.         r = x * x + y * y;
  346.     }
  347.     while ( r >= 1.0 || r == 0.0 );
  348.     double s = sqrt( -2.0 * log(r) / r );
  349.     return mean + x * s * stddev;
  350. }
  351.  
  352. inline double MTRand::operator()()
  353. {
  354.     return rand();
  355. }
  356.  
  357. inline void MTRand::save( uint32* saveArray ) const
  358. {
  359.     register const uint32 *s = state;
  360.     register uint32 *sa = saveArray;
  361.     register int i = N;
  362.     for( ; i--; *sa++ = *s++ ) {}
  363.     *sa = left;
  364. }
  365.  
  366. inline void MTRand::load( uint32 *const loadArray )
  367. {
  368.     register uint32 *s = state;
  369.     register uint32 *la = loadArray;
  370.     register int i = N;
  371.     for( ; i--; *s++ = *la++ ) {}
  372.     left = *la;
  373.     pNext = &state[N-left];
  374. }
  375.  
  376. inline std::ostream& operator<<( std::ostream& os, const MTRand& mtrand )
  377. {
  378.     register const MTRand::uint32 *s = mtrand.state;
  379.     register int i = mtrand.N;
  380.     for( ; i--; os << *s++ << "\t" ) {}
  381.     return os << mtrand.left;
  382. }
  383.  
  384. inline std::istream& operator>>( std::istream& is, MTRand& mtrand )
  385. {
  386.     register MTRand::uint32 *s = mtrand.state;
  387.     register int i = mtrand.N;
  388.     for( ; i--; is >> *s++ ) {}
  389.     is >> mtrand.left;
  390.     mtrand.pNext = &mtrand.state[mtrand.N-mtrand.left];
  391.     return is;
  392. }
  393.  
  394. inline MTRand& MTRand::operator=( const MTRand& o )
  395. {
  396.     if( this == &o ) return (*this);
  397.     register const uint32 *t = o.state;
  398.     register uint32 *s = state;
  399.     register int i = N;
  400.     for( ; i--; *s++ = *t++ ) {}
  401.     left = o.left;
  402.     pNext = &state[N-left];
  403.     return (*this);
  404. }
  405.  
  406. #endif  // MERSENNETWISTER_H
  407.  
  408. // Change log:
  409. //
  410. // v0.1 - First release on 15 May 2000
  411. //      - Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus
  412. //      - Translated from C to C++
  413. //      - Made completely ANSI compliant
  414. //      - Designed convenient interface for initialization, seeding, and
  415. //        obtaining numbers in default or user-defined ranges
  416. //      - Added automatic seeding from /dev/urandom or time() and clock()
  417. //      - Provided functions for saving and loading generator state
  418. //
  419. // v0.2 - Fixed bug which reloaded generator one step too late
  420. //
  421. // v0.3 - Switched to clearer, faster reload() code from Matthew Bellew
  422. //
  423. // v0.4 - Removed trailing newline in saved generator format to be consistent
  424. //        with output format of built-in types
  425. //
  426. // v0.5 - Improved portability by replacing static const int's with enum's and
  427. //        clarifying return values in seed(); suggested by Eric Heimburg
  428. //      - Removed MAXINT constant; use 0xffffffffUL instead
  429. //
  430. // v0.6 - Eliminated seed overflow when uint32 is larger than 32 bits
  431. //      - Changed integer [0,n] generator to give better uniformity
  432. //
  433. // v0.7 - Fixed operator precedence ambiguity in reload()
  434. //      - Added access for real numbers in (0,1) and (0,n)
  435. //
  436. // v0.8 - Included time.h header to properly support time_t and clock_t
  437. //
  438. // v1.0 - Revised seeding to match 26 Jan 2002 update of Nishimura and Matsumoto
  439. //      - Allowed for seeding with arrays of any length
  440. //      - Added access for real numbers in [0,1) with 53-bit resolution
  441. //      - Added access for real numbers from normal (Gaussian) distributions
  442. //      - Increased overall speed by optimizing twist()
  443. //      - Doubled speed of integer [0,n] generation
  444. //      - Fixed out-of-range number generation on 64-bit machines
  445. //      - Improved portability by substituting literal constants for long enum's
  446. //      - Changed license from GNU LGPL to BSD
  447. //
  448. // v1.1 - Corrected parameter label in randNorm from "variance" to "stddev"
  449. //      - Changed randNorm algorithm from basic to polar form for efficiency
  450. //      - Updated includes from deprecated <xxxx.h> to standard <cxxxx> forms
  451. //      - Cleaned declarations and definitions to please Intel compiler
  452. //      - Revised twist() operator to work on ones'-complement machines
  453. //      - Fixed reload() function to work when N and M are unsigned
  454. //      - Added copy constructor and copy operator from Salvador Espana
RAW Paste Data