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