root/trunk/dep/include/mersennetwister/MersenneTwister.h @ 2

Revision 2, 13.6 kB (checked in by yumileroy, 17 years ago)

[svn] * Proper SVN structure

Original author: Neo2003
Date: 2008-10-02 16:23:55-05:00

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