CernVM-FS  2.12.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 <limits> // NOLINT
15 
16 #include <cassert>
17 #include <cmath>
18 #include <cstdlib>
19 
20 
21 #ifdef CVMFS_NAMESPACE_GUARD
22 namespace CVMFS_NAMESPACE_GUARD {
23 #endif
24 
28 class Prng {
29  public:
30  // Cannot throw an exception
31  Prng() throw() {
32  state_ = 0;
33  }
34 
35  void InitSeed(const uint64_t seed) {
36  state_ = seed;
37  }
38 
39  void InitLocaltime() {
40  struct timeval tv_now;
41  int retval = gettimeofday(&tv_now, NULL);
42  assert(retval == 0);
43  state_ = tv_now.tv_usec;
44  }
45 
49  uint32_t Next(const uint64_t boundary) {
50  state_ = a*state_ + c;
51  double scaled_val =
52  static_cast<double>(state_) * static_cast<double>(boundary) /
53  static_cast<double>(18446744073709551616.0);
54  return static_cast<uint32_t>(static_cast<uint64_t>(scaled_val) % boundary);
55  }
56 
60  double NextDouble() {
61  state_ = a*state_ + c;
62  double unit_val = static_cast<double>(state_) /
63  static_cast<double>(18446744073709551616.0);
64  return unit_val;
65  }
71  double NextNormal() {
72  double z, u1, u2;
73  double pi = atan(1) * 4;
74  u1 = NextDouble();
75  u2 = NextDouble();
76  z = sqrt(-2.0 * log(u1)) * cos(2 * pi * u2);
77  return z;
78  }
79 
80 
81  private:
82  // Magic numbers from MMIX
83  // static const uint64_t m = 2^64;
84  static const uint64_t a = 6364136223846793005LLU;
85  static const uint64_t c = 1442695040888963407LLU;
86  uint64_t state_;
87 }; // class Prng
88 
89 #ifdef CVMFS_NAMESPACE_GUARD
90 } // namespace CVMFS_NAMESPACE_GUARD
91 #endif
92 
93 #endif // CVMFS_UTIL_PRNG_H_
Definition: prng.h:28
void InitLocaltime()
Definition: prng.h:39
assert((mem||(size==0))&&"Out Of Memory")
void InitSeed(const uint64_t seed)
Definition: prng.h:35
Prng()
Definition: prng.h:31
double NextNormal()
Definition: prng.h:71
double NextDouble()
Definition: prng.h:60
uint64_t state_
Definition: prng.h:86
uint32_t Next(const uint64_t boundary)
Definition: prng.h:49