Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

How do I generate a random number according to the binomial distribution?

I would like to generate a random integer according to the binomial distribution. That is, I would like to generate a Bin(n,p) random value. That's number between 0 and n in which the probability we get the value k is C(n,k)p^k(1-p)^(n-k).

Here is an inefficient method (which requires n calls to random() ):

def bin_rv(n,p=0.5):
    Generate a binomial random variable with parameters n,p.
    return sum( random() < p for _ in range(n))

Is there a better way to do this (already built into Sage, I hope)?

(In Matlab, this can be done via the binord function and in R with the rbinom function.)