Commit edd4ad52f082978d6f5d40acfd4c879283ee2d29

Authored by Jordi Inglada
1 parent ec7f8f9b
Exists in master

Uniform distribution

Showing 1 changed file with 24 additions and 0 deletions   Show diff stats
include/cbutils.h
... ... @@ -21,6 +21,7 @@
21 21 #include <string>
22 22 #include <sstream>
23 23 #include <vector>
  24 +#include <random>
24 25 namespace cbutils
25 26 {
26 27 // ----------------- String manipulation ---------------------------------------
... ... @@ -85,6 +86,29 @@ Seq tail(const Seq&amp; s)
85 86 return result;
86 87 }
87 88 }// end ns seq
  89 +// ----------------- Random numbers --------------------------------------------
  90 +namespace rand
  91 +{
  92 +template <typename T>
  93 +T uniform(T minvalue, T maxvalue, std::mt19937& engine, std::true_type)
  94 +{
  95 + static std::uniform_int_distribution<T> dist(minvalue, maxvalue);
  96 + return dist(engine);
  97 +}
  98 +template <typename T>
  99 +T uniform(T minvalue, T maxvalue, std::mt19937& engine, std::false_type)
  100 +{
  101 + static std::uniform_real_distribution<T> dist(minvalue, maxvalue);
  102 + return dist(engine);
  103 +}
  104 +template <typename T>
  105 +T uniform(T minvalue, T maxvalue)
  106 +{
  107 + static std::random_device random_device;
  108 + static std::mt19937 engine{random_device()};
  109 + return uniform(minvalue, maxvalue, engine, std::is_integral<T>());
  110 +}
  111 +}// edn ns rand
88 112 // ----------------- Miscellaneous ---------------------------------------------
89 113 namespace misc
90 114 {
... ...