Python 3.12+randomfunction
random.binomialvariate
distributions
The number of successes in n Bernoulli trials with probability p; an int in [0, n] (3.12+).
Syntax
random.binomialvariate(n=1, p=0.5)
This is the only distribution function in random that hands back an int rather than a float. It collapses the loop sum(random.random() < p for _ in range(n)) into a single call, and does it much faster without scaling badly with n. It landed in 3.12 only, so older interpreters raise AttributeError and you write the sum by hand; a negative n or a p outside [0, 1] raises ValueError.
Examples
import random
print(0 <= random.binomialvariate(10, 0.5) <= 10) # → True
print(random.binomialvariate() in (0, 1)) # → True
print(random.binomialvariate(10, 0.0), random.binomialvariate(10, 1.0)) # → 0 10
print(round(sum(random.binomialvariate(10, 0.5) for _ in range(10000)) / 10000)) # → 5
print(random.binomialvariate(10, 1.5)) # → ValueError
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy