CernVM-FS  2.9.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_PRNG_H_
9 #define CVMFS_PRNG_H_
10 
11 #include <stdint.h>
12 #include <sys/time.h>
13 
14 #include <cassert>
15 #include <cmath>
16 #include <cstdlib>
17 
18 #ifdef CVMFS_NAMESPACE_GUARD
19 namespace CVMFS_NAMESPACE_GUARD {
20 #endif
21 
25 class Prng {
26  public:
27  Prng() {
28  state_ = 0;
29  }
30 
31  void InitSeed(const uint64_t seed) {
32  state_ = seed;
33  }
34 
35  void InitLocaltime() {
36  struct timeval tv_now;
37  int retval = gettimeofday(&tv_now, NULL);
38  assert(retval == 0);
39  state_ = tv_now.tv_usec;
40  }
41 
45  uint32_t Next(const uint64_t boundary) {
46  state_ = a*state_ + c;
47  double scaled_val =
48  static_cast<double>(state_) * static_cast<double>(boundary) /
49  static_cast<double>(18446744073709551616.0);
50  return static_cast<uint32_t>(static_cast<uint64_t>(scaled_val) % boundary);
51  }
52 
56  double NextDouble() {
57  state_ = a*state_ + c;
58  double unit_val = static_cast<double>(state_) /
59  static_cast<double>(18446744073709551616.0);
60  return unit_val;
61  }
67  double NextNormal() {
68  double z, u1, u2;
69  double pi = atan(1) * 4;
70  u1 = NextDouble();
71  u2 = NextDouble();
72  z = sqrt(-2.0 * log(u1)) * cos(2 * pi * u2);
73  return z;
74  }
75 
76 
77  private:
78  // Magic numbers from MMIX
79  // static const uint64_t m = 2^64;
80  static const uint64_t a = 6364136223846793005LLU;
81  static const uint64_t c = 1442695040888963407LLU;
82  uint64_t state_;
83 }; // class Prng
84 
85 #ifdef CVMFS_NAMESPACE_GUARD
86 } // namespace CVMFS_NAMESPACE_GUARD
87 #endif
88 
89 #endif // CVMFS_PRNG_H_
Definition: prng.h:25
void InitLocaltime()
Definition: prng.h:35
assert((mem||(size==0))&&"Out Of Memory")
void InitSeed(const uint64_t seed)
Definition: prng.h:31
Prng()
Definition: prng.h:27
double NextNormal()
Definition: prng.h:67
double NextDouble()
Definition: prng.h:56
uint64_t state_
Definition: prng.h:82
uint32_t Next(const uint64_t boundary)
Definition: prng.h:45