diff --git a/.gitignore b/.gitignore index edb4ca0..eaa364d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ +.ccls-cache/ build/ lib/ *.swp +*.json diff --git a/adv/random_generator.h b/adv/random_generator.h index e75d7f3..4520913 100644 --- a/adv/random_generator.h +++ b/adv/random_generator.h @@ -640,6 +640,17 @@ class random_generator { return variate(lower, upper); } + /** + * Geometric Distribution + * https://en.cppreference.com/w/cpp/numeric/random/geometric_distribution + * + * Geo(i;p) = p(1-p)^i where i=0,1,2,... + * + */ + int geometric(const double p) { + return variate(p); + } + /** * [0,1) */ diff --git a/test/test_rngutils.cpp b/test/test_rngutils.cpp index 7f026b5..ab6adde 100644 --- a/test/test_rngutils.cpp +++ b/test/test_rngutils.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include "../adv/rngutils.h" @@ -17,7 +18,7 @@ void test_basic() { printf("\n choose 3:\n"); auto samples = rngutils::choice(population, 3, rng); - for (int s: samples) printf(" %d,", s); + for (int s : samples) printf(" %d,", s); printf("\n"); printf("\n init uniform:\n"); @@ -38,8 +39,21 @@ void test_rng() { std::cout << std::bitset<32>(UINT_MAX) << " " << UINT_MAX << std::endl; } +void test_geo() { + rngutils::default_rng rng; + std::map hist; + for (int n = 0; n < 10000; ++n) { + hist[rng.geometric(0.5)]++; + } + + for (auto p : hist) { + std::cout << p.first << ' ' << std::string(p.second / 100, '*') << '\n'; + } +} + int main(int argc, char *argv[]) { - test_basic(); + // test_basic(); + test_geo(); return 0; }