Distributions
Binomial Probability
Compute P(X=k) for a Binomial(n, p) distribution: the probability of
exactly k successes in n independent trials each with success probability p.
Formula: C(n,k) × p^k × (1−p)^(n−k). Show each piece as a named variable
— the binomial coefficient via math.comb, the success probability mass
p^k, the failure probability mass (1−p)^(n−k) — then multiply. Library:
scipy.stats.binom.pmf(k, n, p).
By hand
Four named pieces make the formula readable: comb=math.comb(5,2)=10,
pk=0.5²=0.25, q=1−0.5=0.5, q_nk=0.5³=0.125. Multiply: prob = 10 ×
0.25 × 0.125 = 0.3125. Each piece is visible in the trace before the final
product.
import math
n = 5
k = 2
p = 0.5
comb = math.comb(n, k)
pk = p ** k
q = 1 - p
q_nk = q ** (n - k)
prob = comb * pk * q_nk
print('RESULT:', round(prob, 6))
import math
1import math2n = 5n ← 5
1import math2n = 53k = 2values this step5nk ← 2
2n = 53k = 24p = 0.5values this step2kp ← 0.5
3k = 24p = 0.55comb = math.comb(n, k)values this step0.5pcomb ← 10
4p = 0.55comb = math.comb(n, k)6pk = p ** kvalues this step10combpk ← 0.25
5comb = math.comb(n, k)6pk = p ** k7q = 1 - pvalues this step0.25pkq ← 0.5
6pk = p ** k7q = 1 - p8q_nk = q ** (n - k)values this step0.5qq_nk ← 0.125
7q = 1 - p8q_nk = q ** (n - k)9prob = comb * pk * q_nkvalues this step0.125q_nkprob ← 0.3125
8q_nk = q ** (n - k)9prob = comb * pk * q_nk10print('RESULT:', round(prob, 6))values this step0.3125probstdout ← RESULT: 0.3125
9prob = comb * pk * q_nk10print('RESULT:', round(prob, 6))values this stepRESULT: 0.3125stdout
With the library
scipy.stats.binom.pmf(k, n, p) applies the same formula internally.
Parameters are (k, n, p) — note the order: k first, then the distribution
parameters n and p.
from scipy.stats import binom
from dalib.display import set_display
set_display()
n = 5
k = 2
p = 0.5
prob = binom.pmf(k, n, p)
print('n:', n, ' k:', k, ' p:', p)
print('RESULT:', round(prob, 6))
n: 5 k: 2 p: 0.5
RESULT: 0.3125
Implementation notes
- C(n,k) counts the number of distinct arrangements of k successes among n
trials.
math.comb(n, k)computes this exactly in integer arithmetic with no floating-point error. - p=0.5 makes the exact-fraction result 0.3125 visible without rounding. The result is exact because 0.5 is representable in binary float.
- The binomial distribution assumes independence between trials and a constant p. Relaxing independence leads to more complex models.
- Cross-reference:
poisson-probability(this chapter) — the Poisson distribution is the limit of Binomial(n, λ/n) as n→∞ with fixed λ.