ASKSAGE: Sage Q&A Forum - Latest question feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Mon, 02 Apr 2012 08:50:18 -0500How do I generate a random number according to the binomial distribution?https://ask.sagemath.org/question/8848/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.)Ed ScheinermanMon, 02 Apr 2012 08:50:18 -0500https://ask.sagemath.org/question/8848/