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

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.

naive.py
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))
library.py
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 λ.