Simulating Coin Flips in C++
Occasionally I have to generate random numbers in C++, and since C++11 was published the langauge now has a massively powerful, flexible library for generating quality random numbers. The only issue is that for the life of me I cannot remember the API. This would probably not be a problem if I used it more frequently, but anyways, this blog post is a reminder for me of how to generate a uniform distribution. The following function simulates a coin toss, i.e. it returns either a 0 or a 1 with equal probability.
auto get_coin_flip()
{
// Generate some seed values using the platform's native
// random device.
static std::random_device r;
static std::seed_seq seeds{ r(), r(), r(), r(), r(), r() };
// Construct a meresenne twister random number generator,
// seeded with the values we just generated. This will give
// us better quality random numbers than the random device
// alone.
static std::mt19937 engine(seeds);
// Create a uniform distribution of int values ranging from
// zero to one, inclusive.
//
// Notice how every variable up to this point is static. This
// is to ensure that they're only ever initialized once during
// the execution of the program. We don't want to generate a
// new random number generator at each function call as we'll
// lose the random state.
static std::uniform_int_distribution<int> dist(0, 1);
// Roll the dice and return the result.
return dist(engine);
}
Hopefully this is useful to somebody. I know I’ll probably refer back to it in the future.