简体   繁体   中英

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.

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.

from random import randint
num_trues = 0

for _ in range(1000):
  num_trues += randint(0, 1)

print(num_trues)

randint produces an integer betweeen the upper and lower bound, inclusive.

This is probably not the most idiomatic way to do this in python and probably not the fastest way. But it works. You could use similar approaches for other distributions of the probability.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM