Skip to content

Commit

Permalink
random_generator: add support for Geometric distribution
Browse files Browse the repository at this point in the history
  • Loading branch information
zzjjzzgggg committed Mar 27, 2019
1 parent 9aef4a4 commit a93a492
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
.ccls-cache/
build/
lib/
*.swp
*.json
11 changes: 11 additions & 0 deletions adv/random_generator.h
Original file line number Diff line number Diff line change
Expand Up @@ -640,6 +640,17 @@ class random_generator {
return variate<Numeric, uniform_distribution>(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<int, std::geometric_distribution>(p);
}

/**
* [0,1)
*/
Expand Down
18 changes: 16 additions & 2 deletions test/test_rngutils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#include <climits>
#include <bitset>
#include <iostream>
#include <map>

#include "../adv/rngutils.h"

Expand All @@ -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");
Expand All @@ -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<int, int> 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;
}

0 comments on commit a93a492

Please sign in to comment.