Random.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // This code is in the public domain -- [email protected]
  2. #include <nvmath/Random.h>
  3. #include <time.h>
  4. using namespace nv;
  5. // Statics
  6. const uint16 Rand48::a0 = 0xE66D;
  7. const uint16 Rand48::a1 = 0xDEEC;
  8. const uint16 Rand48::a2 = 0x0005;
  9. const uint16 Rand48::c0 = 0x000B;
  10. /// Get a random seed based on the current time.
  11. uint Rand::randomSeed()
  12. {
  13. return (uint)time(NULL);
  14. }
  15. void MTRand::initialize( uint32 seed )
  16. {
  17. // Initialize generator state with seed
  18. // See Knuth TAOCP Vol 2, 3rd Ed, p.106 for multiplier.
  19. // In previous versions, most significant bits (MSBs) of the seed affect
  20. // only MSBs of the state array. Modified 9 Jan 2002 by Makoto Matsumoto.
  21. uint32 *s = state;
  22. uint32 *r = state;
  23. int i = 1;
  24. *s++ = seed & 0xffffffffUL;
  25. for( ; i < N; ++i )
  26. {
  27. *s++ = ( 1812433253UL * ( *r ^ (*r >> 30) ) + i ) & 0xffffffffUL;
  28. r++;
  29. }
  30. }
  31. void MTRand::reload()
  32. {
  33. // Generate N new values in state
  34. // Made clearer and faster by Matthew Bellew ([email protected])
  35. uint32 *p = state;
  36. int i;
  37. for( i = N - M; i--; ++p )
  38. *p = twist( p[M], p[0], p[1] );
  39. for( i = M; --i; ++p )
  40. *p = twist( p[M-N], p[0], p[1] );
  41. *p = twist( p[M-N], p[0], state[0] );
  42. left = N, next = state;
  43. }