Skip to content

Instantly share code, notes, and snippets.

@ericdke
Last active October 6, 2020 04:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericdke/a63f4fd22c7f926b664618d96a3eb284 to your computer and use it in GitHub Desktop.
Save ericdke/a63f4fd22c7f926b664618d96a3eb284 to your computer and use it in GitHub Desktop.
C++: random number generator
#include <iostream>
#include <iomanip>
#include <random>
// this template comes from http://stackoverflow.com/a/39183450/2227743
template<class Ty = double, class = std::enable_if<std::is_floating_point<Ty>::value>>
class random_probability_generator {
public:
// default constructor uses single random_device for seeding
random_probability_generator()
: mt_eng{std::random_device{}()}, prob_dist(0.0, 1.0) {}
Ty next() { return prob_dist(mt_eng); }
Ty generate() { return next(); }
private:
std::mt19937 mt_eng;
std::uniform_real_distribution<Ty> prob_dist;
};
// usage
int main(int argc, const char * argv[]) {
// default: for double.
// add a type in the template to change it,
// ex: random_probability_generator<float> pgen;
random_probability_generator<> pgen;
// let's make some random bits
for (int i = 0; i < 1000; i++) {
double p = pgen.generate();
// fmod(floor(p*10), 2) gives a random number between 0 and 1 (because modulo 2)
// use modulo 3 for rnd between 0 and 2, mod 4 for rnd between 0 and 3, etc
double r = fmod(floor(p*10), 2);
std::cout << r;
}
std::cout << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment