random.binomialvariate
Mathematically sum(random() < p for i in range(n)), but fast for any n: it needs about n * p draws for small n * p and a constant number (BTRS rejection) for large ones. So it does NOT give the same numbers as the sum() loop.
Demo
import random random.seed(42) [random.binomialvariate(10, 0.5) for _ in range(8)]
For p > 0.5 it counts failures instead (n - binomialvariate(n, 1 - p)). With n * p < 10 it jumps from success to success with geometric gaps computed by log2; otherwise it uses Hörmann's BTRS rejection method with lgamma, so even a million trials cost only a few draws. The estimate tab approaches the exact probability of 5+ successes, about 0.42 for p = 0.6.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| n | int | no (1) | Number of trials, >= 0. |
| p | float | no (0.5) | Success probability per trial, 0.0 <= p <= 1.0. p = 0 and p = 1 return 0 and n without drawing. |
Return value
int — Number of successes, 0 <= X <= n; mean n * p.
Common patterns
import random failures = random.binomialvariate(500, 0.02)
import random conv_a = random.binomialvariate(visitors, 0.031) conv_b = random.binomialvariate(visitors, 0.034)
import random successes = sum(random.random() < p for _ in range(n))
Examples
Pitfalls
import random random.seed(42) random.binomialvariate(10, 0.5) == sum(random.random() < 0.5 for _ in range(10))
import random random.seed(42) round(sum(random.binomialvariate(20, 0.25) for _ in range(10000)) / 10000, 1) == 20 * 0.25
import random random.seed(42) random.binomialvariate(-1)
import random random.seed(42) random.binomialvariate(0)
When to use
- Counting successes: defects, conversions, heads, hits
- Large n where summing random() < p would be slow
- Python 3.11 and older → sum(random.random() < p for _ in range(n))
- Which trials succeeded (not just how many) → [random.random() < p for _ in range(n)]
- Weighted categories → choices()
Notes
FAQ
In Python 3.12+ use random.binomialvariate(n, p). In older versions sum(random.random() < p for _ in range(n)) gives the same distribution, or use numpy.random.Generator.binomial.