CernVM-FS  2.13.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
prng.h
Go to the documentation of this file.
1 
8 #ifndef CVMFS_UTIL_PRNG_H_
9 #define CVMFS_UTIL_PRNG_H_
10 
11 #include <stdint.h>
12 #include <sys/time.h>
13 
14 #include <cassert>
15 #include <cmath>
16 #include <cstdlib>
17 #include <limits> // NOLINT
18 
19 
20 #ifdef CVMFS_NAMESPACE_GUARD
21 namespace CVMFS_NAMESPACE_GUARD {
22 #endif
23 
27 class Prng {
28  public:
29  // Cannot throw an exception
30  Prng() throw() { state_ = 0; }
31 
32  void InitSeed(const uint64_t seed) { state_ = seed; }
33 
34  void InitLocaltime() {
35  struct timeval tv_now;
36  int retval = gettimeofday(&tv_now, NULL);
37  assert(retval == 0);
38  state_ = tv_now.tv_usec;
39  }
40 
44  uint32_t Next(const uint64_t boundary) {
45  state_ = a * state_ + c;
46  double scaled_val = static_cast<double>(state_)
47  * static_cast<double>(boundary)
48  / static_cast<double>(18446744073709551616.0);
49  return static_cast<uint32_t>(static_cast<uint64_t>(scaled_val) % boundary);
50  }
51 
55  double NextDouble() {
56  state_ = a * state_ + c;
57  double unit_val = static_cast<double>(state_)
58  / static_cast<double>(18446744073709551616.0);
59  return unit_val;
60  }
66  double NextNormal() {
67  double z, u1, u2;
68  double pi = atan(1) * 4;
69  u1 = NextDouble();
70  u2 = NextDouble();
71  z = sqrt(-2.0 * log(u1)) * cos(2 * pi * u2);
72  return z;
73  }
74 
75 
76  private:
77  // Magic numbers from MMIX
78  // static const uint64_t m = 2^64;
79  static const uint64_t a = 6364136223846793005LLU;
80  static const uint64_t c = 1442695040888963407LLU;
81  uint64_t state_;
82 }; // class Prng
83 
84 #ifdef CVMFS_NAMESPACE_GUARD
85 } // namespace CVMFS_NAMESPACE_GUARD
86 #endif
87 
88 #endif // CVMFS_UTIL_PRNG_H_
Definition: prng.h:27
void InitLocaltime()
Definition: prng.h:34
assert((mem||(size==0))&&"Out Of Memory")
void InitSeed(const uint64_t seed)
Definition: prng.h:32
Prng()
Definition: prng.h:30
double NextNormal()
Definition: prng.h:66
double NextDouble()
Definition: prng.h:55
uint64_t state_
Definition: prng.h:81
uint32_t Next(const uint64_t boundary)
Definition: prng.h:44