SolidUtils
FastIntDistribution.hpp
Go to the documentation of this file.
1 
29 #ifndef SOLIDUTILS_INCLUDE_FASTINTDISTRIBUTION_HPP
30 #define SOLIDUTILS_INCLUDE_FASTINTDISTRIBUTION_HPP
31 
32 
33 #include <cstdint>
34 #include <limits>
35 
36 
37 namespace sl
38 {
39 
46 template<typename T>
48 {
49  public:
58  T const min,
59  T const max) :
60  m_min(min),
61  m_range(static_cast<uint64_t>(max-min)+1)
62  {
63  // do nothing
64  }
65 
75  template<class RNG>
76  T operator()(RNG& rng)
77  {
78  static_assert(std::numeric_limits<uint64_t>::max() > \
79  static_cast<uint64_t>(RNG::max() - RNG::min()), \
80  "Unhandled full 64 bit range.");
81 
82  constexpr uint64_t RNG_RANGE = static_cast<uint64_t>(RNG::max() - RNG::min()) + 1;
83 
84  uint64_t const width = m_range / RNG_RANGE;
85 
86  uint64_t num = 0;
87  for (uint64_t i = 0; i <= width; ++i) {
88  num *= static_cast<uint64_t>(RNG_RANGE);
89  num += static_cast<uint64_t>(rng() - RNG::min());
90  }
91  num = num % m_range;
92 
93  return static_cast<T>(num) + m_min;
94  }
95 
96  private:
97  T m_min;
98  uint64_t m_range;
99 
100 };
101 
102 
103 }
104 
105 #endif
106 
107 
Definition: Alloc.hpp:40
FastIntDistribution(T const min, T const max)
Create a new FastIntDistribution which will result in numbers [min,max].
Definition: FastIntDistribution.hpp:57
T operator()(RNG &rng)
Generate a number in the range of [min, max]. The distribution may not be uniform, particularily for larger ranges.
Definition: FastIntDistribution.hpp:76
This distribution is designed to be fast and consistent across platforms. However, it will not be uniform.
Definition: FastIntDistribution.hpp:47