Visualization Library 2.0.0-b3

A lightweight C++ OpenGL middleware for 2D/3D graphics

VL     Star     Watch     Fork     Issue

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