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