Binomial random variable.
Gives the number of successes for *n* independent trials
with the probability of success in each trial being *p*:
sum(random() < p for i in range(n))
Returns an integer in the range:
0 <= X <= n
The integer is chosen with the probability:
P(X == k) = math.comb(n, k) * p ** k * (1 - p) ** (n - k)
The mean (expected value) and variance of the random variable are:
E[X] = n * p
Var[X] = n * p * (1 - p)
>>> # Six roulette wheel spins (weighted sampling with replacement)
>>> choices(['red', 'black', 'green'], [18, 18, 2], k=6)['red', 'green', 'black', 'black', 'red', 'black']
>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value: ten, jack, queen, or king.
>>> deal = sample(['tens', 'low cards'], counts=[16, 36], k=20)
>>> deal.count('tens') / 20
0.15
>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> sum(binomialvariate(n=7, p=0.6) >= 5 for i inrange(10_000)) / 10_000
0.4169
>>> # Probability of the median of 5 samples being in middle two quartiles
>>> deftrial():
... return 2_500 <= sorted(choices(range(10_000), k=5))[2] < 7_500
...
>>> sum(trial()for i inrange(10_000)) / 10_000
0.7958