Search code examples
pythondistribution

Random number distribution that generates bool values according to a Bernoulli distribution in Python


In C++, this can be achieved by:

std::default_random_engine generator;
std::bernoulli_distribution distribution(0.5);
int count=0;  // count number of trues
for (int i=0; i<100000; ++i) if (distribution(generator)) ++count;

I am looking for a Python equivalent.


Solution

  • If you're looking for a solution that lets you adjust p and the sample size, you can use random.choices. This solution can be easily modified to simulate sampling from a Bernoulli distribution when p != 0.5:

    import random
    p = 0.5
    n = 100000
    count = 0
    
    print(sum(random.choices([True, False], [p, 1 - p], k=n)))
    

    I'll also add that there are libraries for sampling from probability distributions (probabilistic programming libraries) such as Pyro. It's overkill for this task, but may be useful if you need something more powerful in the future.