Distributions
Poisson Probability
Compute P(X=k) for a Poisson(λ) distribution: the probability of exactly k
events in a fixed interval given mean rate λ. Formula: (λ^k × e^−λ) / k!.
Three named pieces: lam_k = λ^k, e_neg_lam = math.exp(−λ), k_fact = math.factorial(k). Assemble as numerator / k_fact. Library:
scipy.stats.poisson.pmf(k, lam).
By hand
λ=3, k=2. Three pieces: lam_k = 3²=9, e_neg_lam = e^−3 ≈ 0.049787,
k_fact = 2!=2. Numerator = 9 × 0.049787 ≈ 0.447884. Divide by 2:
prob ≈ 0.224042. Each intermediate is visible before the final division.
naive.py
Replay: real traced execution (multi-file project)
import math
lam = 3
k = 2
lam_k = lam ** k
e_neg_lam = math.exp(-lam)
k_fact = math.factorial(k)
numerator = lam_k * e_neg_lam
prob = numerator / k_fact
print('RESULT:', round(prob, 6))
import math
1import math2lam = 3lam ← 3
1import math2lam = 33k = 2values this step3lamk ← 2
2lam = 33k = 24lam_k = lam ** kvalues this step2klam_k ← 9
3k = 24lam_k = lam ** k5e_neg_lam = math.exp(-lam)values this step9lam_ke_neg_lam ← 0.049787068367863944
4lam_k = lam ** k5e_neg_lam = math.exp(-lam)6k_fact = math.factorial(k)values this step0.049787068367863944e_neg_lamk_fact ← 2
5e_neg_lam = math.exp(-lam)6k_fact = math.factorial(k)7numerator = lam_k * e_neg_lamvalues this step2k_factnumerator ← 0.4480836153107755
6k_fact = math.factorial(k)7numerator = lam_k * e_neg_lam8prob = numerator / k_factvalues this step0.4480836153107755numeratorprob ← 0.22404180765538775
7numerator = lam_k * e_neg_lam8prob = numerator / k_fact9print('RESULT:', round(prob, 6))values this step0.22404180765538775probstdout ← RESULT: 0.224042
8prob = numerator / k_fact9print('RESULT:', round(prob, 6))values this stepRESULT: 0.224042stdout
With the library
scipy.stats.poisson.pmf(k, mu) takes k first, then the rate parameter
(named mu in scipy). Applies the same formula with full floating-point
precision.
library.py
from scipy.stats import poisson
from dalib.display import set_display
set_display()
lam = 3
k = 2
prob = poisson.pmf(k, lam)
print('lambda:', lam, ' k:', k)
print('RESULT:', round(prob, 6))
lambda: 3 k: 2
RESULT: 0.224042
Implementation notes
- The Poisson distribution models counts of rare, independent events in a fixed interval (e.g. 2 phone calls in a minute given mean rate 3/min). λ is both the mean and the variance of the distribution.
- Poisson as the limit of Binomial: Binomial(n, λ/n) → Poisson(λ) as n→∞. For large n and small p with fixed λ=np, the Poisson approximation is computationally cheaper.
math.exp(-lam)andmath.factorial(k)are exact-enough for small k and λ. For very large k, usescipy.stats.poisson.pmfto avoid overflow.- Cross-reference:
binomial-probability(this chapter) for the discrete distribution this approximates in the large-n limit.