Flip a biased coin
12345678910 | #include <random>
int main()
{
std::random_device random_device;
std::mt19937 random_engine{random_device()};
std::bernoulli_distribution coin_distribution{0.25};
bool outcome = coin_distribution(random_engine);
} |
This pattern is licensed under the CC0 Public Domain Dedication.
Intent
Generate a random boolean value according to a bernoulli distribution.
Description
The std::random_device
on line 5
provides a source of uniform non-deterministic random numbers
(where such a source is available). We use this to seed the
Mersenne Twister random number engine,
std::mt19937
, on
line 6. Consider other random number
engines
for different properties.
On line 7, we create a
std::bernoulli_distribution
representing a bernoulli distribution with a success probability of
0.25
. This can be thought of as a biased coin that will land on
heads only a quarter of the time.
Finally, we generate a random number from the random engine,
distributed according to the bernoulli distribution (line 9).
This gives us a boolean value that will be true
with 0.25
probability and false
otherwise.