ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/group/trunk/OOPSE-4/src/math/MersenneTwister.hpp
Revision: 2065
Committed: Tue Mar 1 14:45:45 2005 UTC (19 years, 4 months ago) by tim
File size: 14886 byte(s)
Log Message:
adding MersenneTwister random number generator

File Contents

# Content
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 <cassert>
64 #include <iostream>
65 #include <limits.h>
66 #include <stdio.h>
67 #include <time.h>
68 #include <math.h>
69
70 class MTRand {
71 // Data
72 public:
73 typedef unsigned long uint32; // unsigned integer type, at least 32 bits
74
75 enum { N = 624 }; // length of state vector
76 enum { SAVE = N + 1 }; // length of array for save()
77
78 private:
79 enum { M = 397 }; // period parameter
80
81 uint32 state[N]; // internal state
82 uint32 *pNext; // next value to get from state
83 int left; // number of values left before reload needed
84 int nstrides_;
85 int stride_;
86
87 //Methods
88 public:
89 MTRand( const uint32& oneSeed, int nstrides = 1, int stride = 0); // initialize with a simple uint32
90 MTRand( uint32 *const bigSeed, uint32 const seedLength = N, int nstrides = 1, int stride = 0); // or an array
91 MTRand(int nstrides = 1, int stride = 0); // auto-initialize with /dev/urandom or time() and clock()
92
93 // Do NOT use for CRYPTOGRAPHY without securely hashing several returned
94 // values together, otherwise the generator state can be learned after
95 // reading 624 consecutive values.
96
97 // Access to 32-bit random numbers
98 double rand(); // real number in [0,1]
99 double rand( const double& n ); // real number in [0,n]
100 double randExc(); // real number in [0,1)
101 double randExc( const double& n ); // real number in [0,n)
102 double randDblExc(); // real number in (0,1)
103 double randDblExc( const double& n ); // real number in (0,n)
104 uint32 randInt(); // integer in [0,2^32-1]
105 uint32 randInt( const uint32& n ); // integer in [0,n] for n < 2^32
106 double operator()() { return rand(); } // same as rand()
107
108 // Access to 53-bit random numbers (capacity of IEEE double precision)
109 double rand53(); // real number in [0,1)
110
111 // Access to nonuniform random number distributions
112 double randNorm( const double& mean = 0.0, const double& variance = 0.0 );
113
114 // Re-seeding functions with same behavior as initializers
115 void seed( const uint32 oneSeed );
116 void seed( uint32 *const bigSeed, const uint32 seedLength = N );
117 void seed();
118
119 // Saving and loading generator state
120 void save( uint32* saveArray ) const; // to array of size SAVE
121 void load( uint32 *const loadArray ); // from such array
122 friend std::ostream& operator<<( std::ostream& os, const MTRand& mtrand );
123 friend std::istream& operator>>( std::istream& is, MTRand& mtrand );
124
125 protected:
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) ^ (-loBit(s1) & 0x9908b0dfUL); }
135 static uint32 hash( time_t t, clock_t c );
136 };
137
138
139 inline MTRand::MTRand( const uint32& oneSeed, int nstrides, int stride) : nstrides_(nstrides), stride_(stride) {
140 assert(stride_ < nstrides_ && stride_ >= 0);
141 seed(oneSeed);
142 }
143
144 inline MTRand::MTRand( uint32 *const bigSeed, const uint32 seedLength, int nstrides, int stride) : nstrides_(nstrides), stride_(stride) {
145 assert(stride_ < nstrides_ && stride_ >= 0);
146 seed(bigSeed,seedLength);
147 }
148
149 inline MTRand::MTRand(int nstrides, int stride) : nstrides_(nstrides), stride_(stride){
150 assert(stride_ < nstrides_ && stride_ >= 0);
151 seed();
152 }
153
154 inline double MTRand::rand()
155 { return double(randInt()) * (1.0/4294967295.0); }
156
157 inline double MTRand::rand( const double& n )
158 { return rand() * n; }
159
160 inline double MTRand::randExc()
161 { return double(randInt()) * (1.0/4294967296.0); }
162
163 inline double MTRand::randExc( const double& n )
164 { return randExc() * n; }
165
166 inline double MTRand::randDblExc()
167 { return ( double(randInt()) + 0.5 ) * (1.0/4294967296.0); }
168
169 inline double MTRand::randDblExc( const double& n )
170 { return randDblExc() * n; }
171
172 inline double MTRand::rand53()
173 {
174 uint32 a = randInt() >> 5, b = randInt() >> 6;
175 return ( a * 67108864.0 + b ) * (1.0/9007199254740992.0); // by Isaku Wada
176 }
177
178 inline double MTRand::randNorm( const double& mean, const double& variance )
179 {
180 // Return a real number from a normal (Gaussian) distribution with given
181 // mean and variance by Box-Muller method
182 double r = sqrt( -2.0 * log( 1.0-randDblExc()) ) * variance;
183 double phi = 2.0 * 3.14159265358979323846264338328 * randExc();
184 return mean + r * cos(phi);
185 }
186
187 inline MTRand::uint32 MTRand::randInt()
188 {
189 // Pull a 32-bit integer from the generator state
190 // Every other access function simply transforms the numbers extracted here
191
192 uint32 ranNums[nstrides_];
193
194 for (int i = 0; i < nstrides_; ++i) {
195 if( left == 0 ) {
196 reload();
197 }
198
199 --left;
200
201 register uint32 s1;
202 s1 = *pNext++;
203 s1 ^= (s1 >> 11);
204 s1 ^= (s1 << 7) & 0x9d2c5680UL;
205 s1 ^= (s1 << 15) & 0xefc60000UL;
206 ranNums[i] = s1 ^ (s1 >> 18);
207 }
208
209 return ranNums[stride_];
210 }
211
212 inline MTRand::uint32 MTRand::randInt( const uint32& n )
213 {
214 // Find which bits are used in n
215 // Optimized by Magnus Jonsson (magnus@smartelectronix.com)
216 uint32 used = n;
217 used |= used >> 1;
218 used |= used >> 2;
219 used |= used >> 4;
220 used |= used >> 8;
221 used |= used >> 16;
222
223 // Draw numbers until one is found in [0,n]
224 uint32 i;
225 do
226 i = randInt() & used; // toss unused bits to shorten search
227 while( i > n );
228 return i;
229 }
230
231
232 inline void MTRand::seed( const uint32 oneSeed )
233 {
234 // Seed the generator with a simple uint32
235 initialize(oneSeed);
236 reload();
237 }
238
239
240 inline void MTRand::seed( uint32 *const bigSeed, const uint32 seedLength )
241 {
242 // Seed the generator with an array of uint32's
243 // There are 2^19937-1 possible initial states. This function allows
244 // all of those to be accessed by providing at least 19937 bits (with a
245 // default seed length of N = 624 uint32's). Any bits above the lower 32
246 // in each element are discarded.
247 // Just call seed() if you want to get array from /dev/urandom
248 initialize(19650218UL);
249 register int i = 1;
250 register uint32 j = 0;
251 register int k = ( N > seedLength ? N : seedLength );
252 for( ; k; --k )
253 {
254 state[i] =
255 state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1664525UL );
256 state[i] += ( bigSeed[j] & 0xffffffffUL ) + j;
257 state[i] &= 0xffffffffUL;
258 ++i; ++j;
259 if( i >= N ) { state[0] = state[N-1]; i = 1; }
260 if( j >= seedLength ) j = 0;
261 }
262 for( k = N - 1; k; --k )
263 {
264 state[i] =
265 state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1566083941UL );
266 state[i] -= i;
267 state[i] &= 0xffffffffUL;
268 ++i;
269 if( i >= N ) { state[0] = state[N-1]; i = 1; }
270 }
271 state[0] = 0x80000000UL; // MSB is 1, assuring non-zero initial array
272 reload();
273 }
274
275
276 inline void MTRand::seed()
277 {
278 // Seed the generator with an array from /dev/urandom if available
279 // Otherwise use a hash of time() and clock() values
280
281 // First try getting an array from /dev/urandom
282 FILE* urandom = fopen( "/dev/urandom", "rb" );
283 if( urandom )
284 {
285 uint32 bigSeed[N];
286 register uint32 *s = bigSeed;
287 register int i = N;
288 register bool success = true;
289 while( success && i-- )
290 success = fread( s++, sizeof(uint32), 1, urandom );
291 fclose(urandom);
292 if( success ) { seed( bigSeed, N ); return; }
293 }
294
295 // Was not successful, so use time() and clock() instead
296 seed( hash( time(NULL), clock() ) );
297 }
298
299
300 inline void MTRand::initialize( const uint32 seed )
301 {
302 // Initialize generator state with seed
303 // See Knuth TAOCP Vol 2, 3rd Ed, p.106 for multiplier.
304 // In previous versions, most significant bits (MSBs) of the seed affect
305 // only MSBs of the state array. Modified 9 Jan 2002 by Makoto Matsumoto.
306 register uint32 *s = state;
307 register uint32 *r = state;
308 register int i = 1;
309 *s++ = seed & 0xffffffffUL;
310 for( ; i < N; ++i )
311 {
312 *s++ = ( 1812433253UL * ( *r ^ (*r >> 30) ) + i ) & 0xffffffffUL;
313 r++;
314 }
315 }
316
317
318 inline void MTRand::reload()
319 {
320 // Generate N new values in state
321 // Made clearer and faster by Matthew Bellew (matthew.bellew@home.com)
322 register uint32 *p = state;
323 register int i;
324 for( i = N - M; i--; ++p )
325 *p = twist( p[M], p[0], p[1] );
326 for( i = M; --i; ++p )
327 *p = twist( p[M-N], p[0], p[1] );
328 *p = twist( p[M-N], p[0], state[0] );
329
330 left = N, pNext = state;
331 }
332
333
334 inline MTRand::uint32 MTRand::hash( time_t t, clock_t c )
335 {
336 // Get a uint32 from t and c
337 // Better than uint32(x) in case x is floating point in [0,1]
338 // Based on code by Lawrence Kirby (fred@genesis.demon.co.uk)
339
340 static uint32 differ = 0; // guarantee time-based seeds will change
341
342 uint32 h1 = 0;
343 unsigned char *p = (unsigned char *) &t;
344 for( size_t i = 0; i < sizeof(t); ++i )
345 {
346 h1 *= UCHAR_MAX + 2U;
347 h1 += p[i];
348 }
349 uint32 h2 = 0;
350 p = (unsigned char *) &c;
351 for( size_t j = 0; j < sizeof(c); ++j )
352 {
353 h2 *= UCHAR_MAX + 2U;
354 h2 += p[j];
355 }
356 return ( h1 + differ++ ) ^ h2;
357 }
358
359
360 inline void MTRand::save( uint32* saveArray ) const
361 {
362 register uint32 *sa = saveArray;
363 register const uint32 *s = state;
364 register int i = N;
365 for( ; i--; *sa++ = *s++ ) {}
366 *sa = left;
367 }
368
369
370 inline void MTRand::load( uint32 *const loadArray )
371 {
372 register uint32 *s = state;
373 register uint32 *la = loadArray;
374 register int i = N;
375 for( ; i--; *s++ = *la++ ) {}
376 left = *la;
377 pNext = &state[N-left];
378 }
379
380
381 inline std::ostream& operator<<( std::ostream& os, const MTRand& mtrand )
382 {
383 register const MTRand::uint32 *s = mtrand.state;
384 register int i = mtrand.N;
385 for( ; i--; os << *s++ << "\t" ) {}
386 return os << mtrand.left;
387 }
388
389
390 inline std::istream& operator>>( std::istream& is, MTRand& mtrand )
391 {
392 register MTRand::uint32 *s = mtrand.state;
393 register int i = mtrand.N;
394 for( ; i--; is >> *s++ ) {}
395 is >> mtrand.left;
396 mtrand.pNext = &mtrand.state[mtrand.N-mtrand.left];
397 return is;
398 }
399
400 #endif // MERSENNETWISTER_H
401
402 // Change log:
403 //
404 // v0.1 - First release on 15 May 2000
405 // - Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus
406 // - Translated from C to C++
407 // - Made completely ANSI compliant
408 // - Designed convenient interface for initialization, seeding, and
409 // obtaining numbers in default or user-defined ranges
410 // - Added automatic seeding from /dev/urandom or time() and clock()
411 // - Provided functions for saving and loading generator state
412 //
413 // v0.2 - Fixed bug which reloaded generator one step too late
414 //
415 // v0.3 - Switched to clearer, faster reload() code from Matthew Bellew
416 //
417 // v0.4 - Removed trailing newline in saved generator format to be consistent
418 // with output format of built-in types
419 //
420 // v0.5 - Improved portability by replacing static const int's with enum's and
421 // clarifying return values in seed(); suggested by Eric Heimburg
422 // - Removed MAXINT constant; use 0xffffffffUL instead
423 //
424 // v0.6 - Eliminated seed overflow when uint32 is larger than 32 bits
425 // - Changed integer [0,n] generator to give better uniformity
426 //
427 // v0.7 - Fixed operator precedence ambiguity in reload()
428 // - Added access for real numbers in (0,1) and (0,n)
429 //
430 // v0.8 - Included time.h header to properly support time_t and clock_t
431 //
432 // v1.0 - Revised seeding to match 26 Jan 2002 update of Nishimura and Matsumoto
433 // - Allowed for seeding with arrays of any length
434 // - Added access for real numbers in [0,1) with 53-bit resolution
435 // - Added access for real numbers from normal (Gaussian) distributions
436 // - Increased overall speed by optimizing twist()
437 // - Doubled speed of integer [0,n] generation
438 // - Fixed out-of-range number generation on 64-bit machines
439 // - Improved portability by substituting literal constants for long enum's
440 // - Changed license from GNU LGPL to BSD