Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Probability function to generate values instead of calling random

In my python code there are a few places where I have a population where there is x chance of something happening to each individual, but I just need the amount of people affected.

amount = 0
population = 500
chance = 0.05

for p in range(population):
    if random.random() < chance:
        amount += 1

My gut tells me there must be a less brute force way to do this than calling random.random() 500 times. Some math or stats terminology or function that I don't know.

amount = population * chance * random.random()

is too variable for what I need.

like image 956
Jay Kyburz Avatar asked Feb 18 '26 17:02

Jay Kyburz


1 Answers

The distribution of the sum of n 0-1 random variables, each with probability p is called a binomial distribution with parameters n and p. I believe numpy.random.binomial will do what you want.

like image 199
augurar Avatar answered Feb 21 '26 06:02

augurar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!