HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
UT_FastRandom.h
Go to the documentation of this file.
1 /*
2  * PROPRIETARY INFORMATION. This software is proprietary to
3  * Side Effects Software Inc., and is not to be reproduced,
4  * transmitted, or disclosed in any way without written permission.
5  *
6  * NAME: UT_FastRandom ( UT Library, C++)
7  *
8  * COMMENTS:
9  * An implementation of George Marsaglia's XOR-128 random number
10  * generator. This generator has a period of 2^128-1, is extremely fast, and
11  * unlike the Mersenne Twister, has negligible seeding time.
12  * http://www.jstatsoft.org/v08/i14/paper
13  */
14 
15 #ifndef __UT_FastRandom__
16 #define __UT_FastRandom__
17 
18 #include "UT_API.h"
19 #include <SYS/SYS_Types.h>
20 #include <stdint.h>
21 
23 {
24 public:
26  {
27  setSeed(0);
28  }
29 
30  void setSeed(uint seed)
31  {
32  mySeeds[0] = seed ^ 123456789U;
33  for (int i = 1; i < 4; i++)
34  {
35  // See Knuth TAOCP Vol 12. P. 106 for multiplier
36  mySeeds[i] = 1812433253U *
37  (mySeeds[i-1] ^ (mySeeds[i-1] >> 30)) + i;
38  }
39  }
40 
41  /// Returns a random 32-bit unsigned integer.
43  {
44  // Note: The shift constants are very carefully selected,
45  // so don't change them arbitrarily.
46  uint t;
47  t = mySeeds[0] ^ (mySeeds[0] << 11);
48  mySeeds[0] = mySeeds[1];
49  mySeeds[1] = mySeeds[2];
50  mySeeds[2] = mySeeds[3];
51  mySeeds[3] = (mySeeds[3] ^ (mySeeds[3] >> 19)) ^
52  (t ^ (t >> 8));
53  return mySeeds[3];
54  }
55 
56  /// Returns a random float between [0,1).
57  float frandom()
58  {
59  SYS_FPRealUnionF tmp;
60  tmp.uval = 0x3f800000 | (0x007fffff & urandom());
61  return tmp.fval - CONST_FPREAL32(1.0);
62  }
63 
64 private:
65  uint mySeeds[4];
66 };
67 
68 /// Fast random number generator.
69 /// Reference: https://software.intel.com/en-us/articles/fast-random-number-generator-on-the-intel-pentiumr-4-processor
70 inline int UTfastRand(uint &seed)
71 {
72  seed = (214013*seed+2531011);
73 
74  return (seed>>16)&0x7FFF;
75 }
76 
77 /// Fast random number generator. Float variant, with values in [0,1).
78 inline float UTfastRandF(uint &seed)
79 {
80  return float(UTfastRand(seed)) / (INT16_MAX-1);
81 }
82 
83 #endif // __UT_FastRandom__
float frandom()
Returns a random float between [0,1).
Definition: UT_FastRandom.h:57
uint urandom()
Returns a random 32-bit unsigned integer.
Definition: UT_FastRandom.h:42
#define UT_API
Definition: UT_API.h:14
int UTfastRand(uint &seed)
Definition: UT_FastRandom.h:70
IMATH_NAMESPACE::V2f float
void setSeed(uint seed)
Definition: UT_FastRandom.h:30
float UTfastRandF(uint &seed)
Fast random number generator. Float variant, with values in [0,1).
Definition: UT_FastRandom.h:78
GLdouble t
Definition: glad.h:2397
#define CONST_FPREAL32(c)
Definition: SYS_Types.h:325
unsigned int uint
Definition: SYS_Types.h:45