All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Random.h
Go to the documentation of this file.
1 #ifndef RANDOM_H_
2 #define RANDOM_H_
3 
4 /*
5  * Random.h
6  *
7  * Created on: 02.01.2014
8  * Author: FJW
9  */
10 
11 #include <cassert>
12 #include <cstddef>
13 #include <cstdint>
14 #include <random>
15 #include <stdexcept>
16 #include "Log.h"
17 
18 namespace Aux {
19 
25 namespace Random {
26 
32 void setSeed(uint64_t seed, bool useThreadId);
33 
37 uint64_t getSeed();
38 
42 std::mt19937_64& getURNG();
43 
44 
50 uint64_t integer();
51 uint64_t integer(uint64_t upperBound);
52 uint64_t integer(uint64_t lowerBound, uint64_t upperBound);
53 
59 double real();
60 double real(double upperBound);
61 double real(double lowerBound, double upperBound);
62 
67 double probability();
68 
73 std::size_t index(std::size_t max);
74 
80 //uint64_t binomial(double n, double p);
81 
82 
86 template<typename Container>
87 typename Container::const_reference choice(const Container& container) {
88  return container[index(container.size())];
89 }
90 
91 
95 template <typename Element>
96 const Element& weightedChoice(const std::vector<std::pair<Element, double>>& weightedElements) {
97  if (weightedElements.size() == 0)
98  throw std::runtime_error("Random::weightedChoice: input size equal to 0");
99  double total = 0.0;
100  for (const auto& entry : weightedElements) {
101  assert(entry.second >= 0.0 && "This algorithm only works with non-negative weights");
102  total += entry.second;
103  }
104  double r = Aux::Random::real(total);
105  for (const auto& entry : weightedElements) {
106  if (r < entry.second) {
107  return entry.first;
108  }
109  r -= entry.second;
110  }
111  throw std::runtime_error("Random::weightedChoice: should never get here"); // should never get here
112 }
113 
114 } // namespace Random
115 } // namespace Aux
116 
117 
118 #endif /* RANDOM_H_ */
double real()
Definition: Random.cpp:77
std::size_t index(std::size_t max)
Definition: Random.cpp:95
uint64_t integer()
Definition: Random.cpp:64
Container::const_reference choice(const Container &container)
Definition: Random.h:87
const Element & weightedChoice(const std::vector< std::pair< Element, double >> &weightedElements)
Definition: Random.h:96
void setSeed(uint64_t seed, bool useThreadId)
Sets the random seed that is used globally.
Definition: Random.cpp:33
uint64_t getSeed()
Definition: Random.cpp:41
double probability()
Definition: Random.cpp:90
std::mt19937_64 & getURNG()
Definition: Random.cpp:54