ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/group/trunk/OOPSE-4/src/math/MersenneTwister.hpp
Revision: 2066
Committed: Tue Mar 1 15:26:13 2005 UTC (19 years, 4 months ago) by gezelter
File size: 15610 byte(s)
Log Message:
Making small modifications to allow for use on MPI machines

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