KrisLibrary  1.0.0
utils/random.h
1 #ifndef UTILS_RANDOM_H
2 #define UTILS_RANDOM_H
3 
4 #include <stdlib.h>
5 #include <limits.h>
6 
9 
25 struct StandardRNG
26 {
27  static inline void seed(unsigned long n) { srand(n); }
28  static inline long int maxValue() { return RAND_MAX; }
29  static inline long int randInt() { return rand(); }
30  static inline float randFloat() { return float(rand())/float(RAND_MAX); }
31  static inline double randDouble() { return double(rand())/double(RAND_MAX); }
32 
34  static inline long int randInt(long int n) { return randInt()%n; }
35  static inline float randFloat(float a, float b) {
36  float t = randFloat();
37  return a + t*(b-a);
38  }
39  static inline double randDouble(double a, double b) {
40  double t = randDouble();
41  return a + t*(b-a);
42  }
43 };
44 
45 
46 #if 0
47 struct RNG32
50 {
51  inline void seed(unsigned long n) { state = n; }
52  inline unsigned int maxValue() const { return UINT_MAX; }
53  inline unsigned long randLong()
54  {
55  state = 1664525L*state + 1013904223L;
56  return state;
57  }
58  inline long int randInt() { return (long int)randLong(); }
59  inline float randFloat()
60  {
61  unsigned long itemp;
62  static unsigned long jflone = 0x3f800000;
63  static unsigned long jflmsk = 0x007fffff;
64 
65  itemp = jflone | (jflmsk & randLong());
66  return (*(float *)&itemp)-1.0f;
67  }
68 
70  inline double randDouble()
71  {
72  unsigned long r[2];
73  r[0] = randLong();
74  r[1] = randLong();
75  static unsigned long jflone = 0x3ff00000;
76  static unsigned long jflmsk = 0x000fffff;
77  r[0] = jflone | (jflmsk & r[0]);
78  double d = *(double*)&r[0];
79  return d-1.0;
80  }
81 
82  //helpers
83  inline long int randInt(int n) { return randInt()%n; }
84  inline float randFloat(float a, float b) {
85  float t = randFloat();
86  return a + t*(b-a);
87  }
88  inline double randDouble(double a, double b) {
89  double t = randDouble();
90  return a + t*(b-a);
91  }
92 
93  unsigned long state;
94 };
95 #endif // 0
96 
98 #ifndef _WIN32
99 struct RNG48
100 {
101  static inline void seed(unsigned long n) { srand48(n); }
102  static inline long int maxValue() { return INT_MAX; }
103  static inline long int randInt() { return lrand48(); }
104  static inline float randFloat() { return (float)drand48(); }
105  static inline double randDouble() { return drand48(); }
106 
107  static inline long int randInt(int n) { return randInt()%n; }
108  static inline float randFloat(float a, float b) {
109  float t = randFloat();
110  return a + t*(b-a);
111  }
112  static inline double randDouble(double a, double b) {
113  double t = randDouble();
114  return a + t*(b-a);
115  }
116 };
117 #endif
118 
121 #endif
uses the ANSI C rand48 functions
Definition: utils/random.h:99
Interface for a random number generator.
Definition: utils/random.h:25
static long int randInt(long int n)
helpers
Definition: utils/random.h:34