openMSX
random.hh
Go to the documentation of this file.
1 #ifndef RANDOM_HH
2 #define RANDOM_HH
3 
4 #include <random>
5 
8 inline auto& global_urng()
9 {
10  static std::minstd_rand0 u;
11  return u;
12 }
13 
16 inline void randomize()
17 {
18  static std::random_device rd;
19  global_urng().seed(rd());
20 }
21 
24 inline bool random_bool()
25 {
26  // Note: this is only 100% uniform if 'generator.max() -
27  // generator().min() + 1' is even. This is the case for
28  // std::minstd_rand0.
29  auto& generator = global_urng();
30  return generator() & 1;
31 }
32 
38 inline int random_int(int from, int thru)
39 {
40  static std::uniform_int_distribution<int> d;
41  using parm_t = decltype(d)::param_type;
42  return d(global_urng(), parm_t{from, thru});
43 }
44 
50 inline float random_float(float from, float upto)
51 {
52  static std::uniform_real_distribution<float> d;
53  using parm_t = decltype(d)::param_type;
54  return d(global_urng(), parm_t{from, upto});
55 }
56 
67 inline uint32_t random_32bit()
68 {
69  static std::uniform_int_distribution<uint32_t> d;
70  using parm_t = decltype(d)::param_type;
71  return d(global_urng(), parm_t{0, 0xffffffff});
72 }
73 
74 #endif
uint32_t random_32bit()
Return a random 32-bit value.
Definition: random.hh:67
void randomize()
Seed the (shared) random number generator.
Definition: random.hh:16
int random_int(int from, int thru)
Return a random integer in the range [from, thru] (note: closed interval).
Definition: random.hh:38
float random_float(float from, float upto)
Return a random float in the range [from, upto) (note: half-open interval).
Definition: random.hh:50
bool random_bool()
Return a random boolean value.
Definition: random.hh:24
auto & global_urng()
Return reference to a (shared) global random number generator.
Definition: random.hh:8