WFMath 1.0.2
MersenneTwister.h
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// changed the #ifndef for wfmath in case someone uses both the lib
58// and the identical header separately
59
60#ifndef MERSENNETWISTER_WFMATH_H
61#define MERSENNETWISTER_WFMATH_H
62
63// Not thread safe (unless auto-initialization is avoided and each thread has
64// its own MTRand object)
65
66#include <iosfwd>
67#include <climits>
68#include <cmath>
69
70// namespace safety for inclusion in the lib
71
72namespace WFMath {
73
74class MTRand {
75// Data
76public:
77 typedef unsigned long uint32; // unsigned integer type, at least 32 bits
78
79 static const uint32 N = 624; // length of state vector
80 static const uint32 SAVE = N + 1; // length of array for save()
81
82protected:
83 static const uint32 M = 397; // period parameter
84
85 uint32 state[N]; // internal state
86 uint32 *pNext; // next value to get from state
87 int left; // number of values left before reload needed
88
89
90//Methods
91public:
92 MTRand( const uint32& oneSeed ); // initialize with a simple uint32
93 MTRand( uint32 *const bigSeed, uint32 const seedLength = N ); // or an array
94 MTRand(); // auto-initialize with /dev/urandom or time() and clock()
95
96 // Do NOT use for CRYPTOGRAPHY without securely hashing several returned
97 // values together, otherwise the generator state can be learned after
98 // reading 624 consecutive values.
99
100 // Access to 32-bit random numbers
101 template<typename FloatT>
102 FloatT rand(); // real number in [0,1]
103 float randf(); // real number in [0,1]
104 float randf( const float& n ); // real number in [0,n]
105 double rand(); // real number in [0,1]
106 double rand( const double& n ); // real number in [0,n]
107 double randExc(); // real number in [0,1)
108 double randExc( const double& n ); // real number in [0,n)
109 double randDblExc(); // real number in (0,1)
110 double randDblExc( const double& n ); // real number in (0,n)
111 uint32 randInt(); // integer in [0,2^32-1]
112 uint32 randInt( const uint32& n ); // integer in [0,n] for n < 2^32
113 double operator()() { return rand(); } // same as rand()
114
115 // Access to 53-bit random numbers (capacity of IEEE double precision)
116 double rand53(); // real number in [0,1)
117
118 // Access to nonuniform random number distributions
119 double randNorm( const double& mean = 0.0, const double& variance = 0.0 );
120
121 // Re-seeding functions with same behavior as initializers
122 void seed( const uint32 oneSeed );
123 void seed( uint32 *const bigSeed, const uint32 seedLength = N );
124 void seed();
125
126 // Saving and loading generator state
127 void save( uint32* saveArray ) const; // to array of size SAVE
128 void load( uint32 *const loadArray ); // from such array
129 friend std::ostream& operator<<( std::ostream& os, const MTRand& mtrand );
130 friend std::istream& operator>>( std::istream& is, MTRand& mtrand );
131
132 static MTRand instance;
133
134protected:
135 void initialize( const uint32 oneSeed );
136 void reload();
137 uint32 hiBit( const uint32& u ) const { return u & 0x80000000UL; }
138 uint32 loBit( const uint32& u ) const { return u & 0x00000001UL; }
139 uint32 loBits( const uint32& u ) const { return u & 0x7fffffffUL; }
140 uint32 mixBits( const uint32& u, const uint32& v ) const
141 { return hiBit(u) | loBits(v); }
142 uint32 twist( const uint32& m, const uint32& s0, const uint32& s1 ) const
143 { return m ^ (mixBits(s0,s1)>>1) ^ (-loBit(s1) & 0x9908b0dfUL); }
144};
145
146
147inline MTRand::MTRand( const uint32& oneSeed ) : pNext(0), left(0)
148 { seed(oneSeed); }
149
150inline MTRand::MTRand( uint32 *const bigSeed, const uint32 seedLength ) : pNext(0), left(0)
151 { seed(bigSeed,seedLength); }
152
153inline MTRand::MTRand() : pNext(0), left(0)
154 { seed(); }
155
156template<>
157inline float MTRand::rand<float>()
158 { return float(randInt()) * (1.0f/4294967295.0f); }
159
160template<>
161inline double MTRand::rand<double>()
162 { return double(randInt()) * (1.0/4294967295.0); }
163
164inline float MTRand::randf()
165 { return float(randInt()) * (1.0f/4294967295.0f); }
166
167inline float MTRand::randf( const float& n )
168 { return randf() * n; }
169
170inline double MTRand::rand()
171 { return double(randInt()) * (1.0/4294967295.0); }
172
173inline double MTRand::rand( const double& n )
174 { return rand() * n; }
175
176inline double MTRand::randExc()
177 { return double(randInt()) * (1.0/4294967296.0); }
178
179inline double MTRand::randExc( const double& n )
180 { return randExc() * n; }
181
182inline double MTRand::randDblExc()
183 { return ( double(randInt()) + 0.5 ) * (1.0/4294967296.0); }
184
185inline double MTRand::randDblExc( const double& n )
186 { return randDblExc() * n; }
187
188inline double MTRand::rand53()
189{
190 uint32 a = randInt() >> 5, b = randInt() >> 6;
191 return ( a * 67108864.0 + b ) * (1.0/9007199254740992.0); // by Isaku Wada
192}
193
194inline double MTRand::randNorm( const double& mean, const double& variance )
195{
196 // Return a real number from a normal (Gaussian) distribution with given
197 // mean and variance by Box-Muller method
198 double r = std::sqrt( -2.0 * std::log( 1.0-randDblExc()) ) * variance;
199 double phi = 2.0 * 3.14159265358979323846264338328 * randExc();
200 return mean + r * std::cos(phi);
201}
202
203inline MTRand::uint32 MTRand::randInt()
204{
205 // Pull a 32-bit integer from the generator state
206 // Every other access function simply transforms the numbers extracted here
207
208 if( left == 0 ) reload();
209 --left;
210
211 register uint32 s1;
212 s1 = *pNext++;
213 s1 ^= (s1 >> 11);
214 s1 ^= (s1 << 7) & 0x9d2c5680UL;
215 s1 ^= (s1 << 15) & 0xefc60000UL;
216 return ( s1 ^ (s1 >> 18) );
217}
218
219inline MTRand::uint32 MTRand::randInt( const uint32& n )
220{
221 // Find which bits are used in n
222 // Optimized by Magnus Jonsson (magnus@smartelectronix.com)
223 uint32 used = n;
224 used |= used >> 1;
225 used |= used >> 2;
226 used |= used >> 4;
227 used |= used >> 8;
228 used |= used >> 16;
229
230 // Draw numbers until one is found in [0,n]
231 uint32 i;
232 do
233 i = randInt() & used; // toss unused bits to shorten search
234 while( i > n );
235 return i;
236}
237
238
239inline void MTRand::seed( const uint32 oneSeed )
240{
241 // Seed the generator with a simple uint32
242 initialize(oneSeed);
243 reload();
244}
245
246
247inline void MTRand::seed( uint32 *const bigSeed, const uint32 seedLength )
248{
249 // Seed the generator with an array of uint32's
250 // There are 2^19937-1 possible initial states. This function allows
251 // all of those to be accessed by providing at least 19937 bits (with a
252 // default seed length of N = 624 uint32's). Any bits above the lower 32
253 // in each element are discarded.
254 // Just call seed() if you want to get array from /dev/urandom
255 initialize(19650218UL);
256 register unsigned i = 1;
257 register uint32 j = 0;
258 register unsigned k = ( N > seedLength ? N : seedLength );
259 for( ; k; --k )
260 {
261 state[i] =
262 state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1664525UL );
263 state[i] += ( bigSeed[j] & 0xffffffffUL ) + j;
264 state[i] &= 0xffffffffUL;
265 ++i; ++j;
266 if( i >= N ) { state[0] = state[N-1]; i = 1; }
267 if( j >= seedLength ) j = 0;
268 }
269 for( k = N - 1; k; --k )
270 {
271 state[i] =
272 state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1566083941UL );
273 state[i] -= i;
274 state[i] &= 0xffffffffUL;
275 ++i;
276 if( i >= N ) { state[0] = state[N-1]; i = 1; }
277 }
278 state[0] = 0x80000000UL; // MSB is 1, assuring non-zero initial array
279 reload();
280}
281
282
283inline void MTRand::initialize( const uint32 seed )
284{
285 // Initialize generator state with seed
286 // See Knuth TAOCP Vol 2, 3rd Ed, p.106 for multiplier.
287 // In previous versions, most significant bits (MSBs) of the seed affect
288 // only MSBs of the state array. Modified 9 Jan 2002 by Makoto Matsumoto.
289 register uint32 *s = state;
290 register uint32 *r = state;
291 register unsigned i = 1;
292 *s++ = seed & 0xffffffffUL;
293 for( ; i < N; ++i )
294 {
295 *s++ = ( 1812433253UL * ( *r ^ (*r >> 30) ) + i ) & 0xffffffffUL;
296 r++;
297 }
298}
299
300
301inline void MTRand::reload()
302{
303 // Generate N new values in state
304 // Made clearer and faster by Matthew Bellew (matthew.bellew@home.com)
305 register uint32 *p = state;
306 register int i;
307 for( i = N - M; i--; ++p )
308 *p = twist( p[M], p[0], p[1] );
309 for( i = M; --i; ++p )
310 *p = twist( p[M-N], p[0], p[1] );
311 *p = twist( p[M-N], p[0], state[0] );
312
313 left = N, pNext = state;
314}
315
316
317
318inline void MTRand::save( uint32* saveArray ) const
319{
320 register uint32 *sa = saveArray;
321 register const uint32 *s = state;
322 register int i = N;
323 for( ; i--; *sa++ = *s++ ) {}
324 *sa = left;
325}
326
327
328inline void MTRand::load( uint32 *const loadArray )
329{
330 register uint32 *s = state;
331 register uint32 *la = loadArray;
332 register int i = N;
333 for( ; i--; *s++ = *la++ ) {}
334 left = *la;
335 pNext = &state[N-left];
336}
337
338
339} // namespace
340
341#endif // MERSENNETWISTER_H
342
343// Change log:
344//
345// v0.1 - First release on 15 May 2000
346// - Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus
347// - Translated from C to C++
348// - Made completely ANSI compliant
349// - Designed convenient interface for initialization, seeding, and
350// obtaining numbers in default or user-defined ranges
351// - Added automatic seeding from /dev/urandom or time() and clock()
352// - Provided functions for saving and loading generator state
353//
354// v0.2 - Fixed bug which reloaded generator one step too late
355//
356// v0.3 - Switched to clearer, faster reload() code from Matthew Bellew
357//
358// v0.4 - Removed trailing newline in saved generator format to be consistent
359// with output format of built-in types
360//
361// v0.5 - Improved portability by replacing static const int's with enum's and
362// clarifying return values in seed(); suggested by Eric Heimburg
363// - Removed MAXINT constant; use 0xffffffffUL instead
364//
365// v0.6 - Eliminated seed overflow when uint32 is larger than 32 bits
366// - Changed integer [0,n] generator to give better uniformity
367//
368// v0.7 - Fixed operator precedence ambiguity in reload()
369// - Added access for real numbers in (0,1) and (0,n)
370//
371// v0.8 - Included time.h header to properly support time_t and clock_t
372//
373// v1.0 - Revised seeding to match 26 Jan 2002 update of Nishimura and Matsumoto
374// - Allowed for seeding with arrays of any length
375// - Added access for real numbers in [0,1) with 53-bit resolution
376// - Added access for real numbers from normal (Gaussian) distributions
377// - Increased overall speed by optimizing twist()
378// - Doubled speed of integer [0,n] generation
379// - Fixed out-of-range number generation on 64-bit machines
380// - Improved portability by substituting literal constants for long enum's
381// - Changed license from GNU LGPL to BSD
Generic library namespace.
Definition atlasconv.h:45