Unpredictable outcomes, predictable averages
A seed cooperative in western Kenya tests a new maize variety: each seed germinates with probability about , and nobody can say which seeds will fail. Yet of seeds, the cooperative can promise that between roughly and will germinate, and be right about times in . A call centre in Manila cannot predict when the next call will come, but it can staff its desks because the number of calls per minute follows a stable pattern. A detector in Chile's Atacama desert counts cosmic-ray muons arriving at random moments; the counts per hour cluster tightly around their average.
Individual outcomes are unpredictable; aggregates are predictable, within quantifiable limits. Probability theory explains this. It answers four questions about a random quantity:
- What is its long-run average? (Expectation.)
- How far does it typically stray from that average? (Variance.)
- Why do averages of many independent repetitions settle down, and how fast? (The law of large numbers.)
- Why do their fluctuations so often take the shape of the same bell curve? (The central limit theorem.)
This lesson assumes the rules of probability — conditional probability, independence of events, Bayes' theorem — from probability rules, and sums, integrals and series from single-variable calculus.
The Galton board
Drop a ball through rows of pins. At each pin it bounces left or right with probability , independently. Its final slot is the number of rightward bounces, a sum of independent coin flips. One ball's path is unpredictable; but drop a thousand and a shape appears.
Many small independent pushes
Each ball's slot is a sum of 12 coin flips. Compare the histogram with the exact binomial counts and the normal curve, then change the number of rows.
- balls in each bin
- exact binomial expectation
- normal approximation
- path of the latest ball
Average bin
Simulated5.97
Exactn/2 = 6
Balls in bin 6
Simulated228
Exact≈ 225.6
Simulation of 1,000 balls through 12 rows: the average bin was 5.97. The exact average is half the number of rows.
Evidence, not proofThis is a simulation of 1,000 balls (run 1) using a seeded random number generator. It is evidence, not proof: the exact values come from mathematics, and a new run gives slightly different numbers.
Bin j collects the balls that bounced right j times. C(n, j) of the 2ⁿ equally likely paths lead there, so the exact chance is C(n, j)/2ⁿ. With many rows this binomial shape is close to a normal curve (the central limit theorem).
Three things are visible already, and the rest of the lesson makes each precise:
- The balls pile up around the middle, : the expectation of is .
- The width of the pile grows, but only like : the standard deviation of is . So the proportion of right bounces has spread , which shrinks: this is the law of large numbers.
- The pile has a characteristic bell shape, whatever the details: this is the central limit theorem.
Random variables and their distributions
Definition— probability space
A probability space consists of a set of outcomes, a collection of subsets of called events (closed under complements and countable unions, and containing ), and a function with that is countably additive: for pairwise disjoint events (Kolmogorov's axioms).
When is countable we may take every subset to be an event. For continuous models (a uniformly random point of , say) this is impossible, and making the definitions fully rigorous requires measure theory; we use its results where needed and say so.
Definition— random variable, distribution, distribution function
A random variable is a function such that is an event for every . Its distribution (or law) is the probability measure on , and its distribution function is . Every distribution function is non-decreasing and right-continuous, with as and as , and it determines the distribution.
Two kinds of distribution cover most examples:
- is discrete if it takes values in a countable set ; its probability mass function is , with .
- is continuous with density if and for all ; then , wherever is continuous, and for every single .
Definition— expectation and variance
The expectation (mean) of is
defined only when the sum or integral converges absolutely: , resp. . More generally, for a function , or (the "law of the unconscious statistician"), again when absolutely convergent. If exists, the variance is and the standard deviation is .
Expanding the square and using linearity (proved below) gives the computing formula , and also : shifting does not change spread, and scaling by scales the standard deviation by .
Definition— joint distribution, independence, covariance
Random variables on the same space have a joint distribution: a joint mass function or a joint density ; the marginals are recovered by summing or integrating out the other variable. and are independent if for all intervals (equivalently, all Borel sets) ; for discrete variables this means , and for densities . A family is (mutually) independent if this product rule holds for every finite subfamily; pairwise independent asks it only for pairs, which is weaker. When the second moments are finite, the covariance is
the correlation is , and are uncorrelated if .
Note
. Indeed, with and , the quadratic is never negative, so its discriminant is : . This is the Cauchy–Schwarz inequality, and the viewpoints section explains why it appears here.
A gallery of distributions
Seven distributions do most of the work in applications. Write .
| Distribution | Mass function or density | Mean | Variance | Models |
|---|---|---|---|---|
| Bernoulli | , | one yes/no trial | ||
| Binomial | , | successes in independent trials | ||
| Geometric | , | trials up to the first success | ||
| Poisson | , | counts of rare events | ||
| Uniform | on | a point chosen "at random" | ||
| Exponential | , | waiting times without memory | ||
| Normal | sums of many small effects |
The binomial row is derived with indicators in the next section. Here are the others.
Example— Geometric: differentiate the geometric series
For , , and a power series may be differentiated term by term inside its radius of convergence: and . Hence, for ,
so . Rolling a fair die until the first six takes rolls on average.
Example— Poisson: shift the index
, and in the same way , so . Mean equals variance — a quick test of whether count data could be Poisson.
Example— Uniform and exponential: integrate
For uniform on : , , so ; the uniform on is , giving the table entries. For exponential with rate , integration by parts gives and , so . Its survival function is , and therefore
This memoryless property says that a component that has survived hours is "as good as new". Among distributions on with a density, only the exponential ones have it (the survival function must satisfy , and the only monotone solutions are exponentials).
Example— Normal: the Gaussian integral
Let . In polar coordinates, , so is a density: the standard normal . By symmetry , and integrating by parts, . Then has density , mean and variance . We write ; it has no elementary formula, and , , .
Normal densities
The shaded area under the standard normal between −1 and 1 is about 0.683. Move m and s: the curve shifts and stretches, but the total area stays 1.
- N(m, s²)
- N(0, 1)
- Signed area: above the axis counts as positive, below (hatched) as negative
- N(m, s²): y = 0.266
- N(0, 1): y = 0.242
- Signed area from −1 to 1 ≈ 0.6827 (numerical integration)
Example— Non-examples: when the mean does not exist
The Cauchy density is symmetric about , yet , so is undefined — not . (It is the tangent of a uniform random angle in .) In the St Petersburg game you win coins with probability , ; then . Both examples will show that the limit theorems really need their hypotheses.
Theorem— Theorem (Poisson limit of the binomial)
Fix and . Then as .
Proof
For and , rewrite the left side as
The second factor is a product of terms ; the third tends to (take logarithms: by ); the fourth tends to . Multiply the limits.
∎
So when there are many independent opportunities, each with a small chance, the number of successes is approximately Poisson. Ladislaus Bortkiewicz's 1898 study of deaths from horse kicks in Prussian cavalry corps — rare, independent accidents — is the classic fit; typing errors per page, mutations per genome per generation and goals per football match are often modelled the same way.
Linearity of expectation and indicator variables
Theorem— Theorem (linearity of expectation)
If and have finite expectations and , then has finite expectation and . No independence is needed.
Proof
We give the proof for discrete with joint mass function ; for general random variables it is the linearity of the integral in measure theory. By the law of the unconscious statistician for , and since makes every sum below absolutely convergent (so it may be rearranged),
The inner sums are the marginals, so this is .
∎
The indicator of an event is the random variable that equals on and off it. It is Bernoulli, so . Combining this with linearity gives one of the most useful tricks in probability: to find the expected number of things that happen, add up their probabilities — even when the events are dependent.
Example— The binomial mean and the number of runs
If counts successes in trials, each succeeding with probability , then , so — no binomial coefficients needed, and the trials need not even be independent. Similarly, in flips of a fair coin the number of places where heads is immediately followed by heads is a sum of indicators, each with probability , so its expectation is , although overlapping pairs such as HHH are far from independent.
Example— Fixed points of a random permutation
Shuffle cards labelled (or return hats to their owners at random). Let be the number of cards that end up in their own position, and the event "card is in place". Then and , so
The events are dependent (if cards are in place, so is the last), but linearity does not care. The variance needs the dependence: for , , so , and by the variance-of-a-sum formula below,
The Lean section proves in a completely different way, from Burnside's lemma in group theory, and the first experiment below checks all permutations for .
Example— Collecting stickers
A school in Accra trades stickers: there are different ones, and each packet contains one, uniformly at random. How many packets until the album is complete? After distinct stickers, each new packet brings a new one with probability , so the waiting time for the -th new sticker is geometric with mean . By linearity,
In general the coupon collector needs draws on average.
Independence, covariance and the variance of a sum
Theorem— Theorem (product rule for independent variables)
If and are independent with finite expectations, then has finite expectation and . Consequently independent variables with finite variances are uncorrelated.
Proof
Discrete case: independence gives , so , and the same computation without absolute values gives . For densities the argument is identical with and Fubini's theorem.
∎
Theorem— Theorem (variance of a sum)
If have finite variances, then
In particular, if the are pairwise uncorrelated — for instance pairwise independent — then the variance of the sum is the sum of the variances.
Proof
Let . By linearity, , so the variance of the sum is . The diagonal terms are the variances, and each unordered pair contributes .
∎
Two consequences we use constantly. The binomial variance: the indicators of independent trials are independent, each with variance , so . The variance of a sample mean: if are pairwise uncorrelated with common variance , then has . Averaging measurements divides the standard deviation by — the law behind every margin of error.
Example— The product rule needs a hypothesis
Let for one fair coin. Then , but : here . And note that for independent , — the variances still add, because .
Example— Uncorrelated but not independent
Let be uniform on and . Then and , so . But is a function of : , whereas . Covariance measures only linear dependence. (This example is checked in Lean below.)
Inequalities and the law of large numbers
Theorem— Theorem (Markov's inequality)
If has finite expectation and , then .
Proof
Pointwise, : where the left side is , and elsewhere it is . Expectation is monotone (a consequence of linearity and for ), so .
∎
Theorem— Theorem (Chebyshev's inequality)
If has mean and finite variance , then for every , . Equivalently, for (when ).
Proof
The events and are the same. Apply Markov's inequality to the non-negative variable , whose expectation is , with .
∎
Chebyshev's inequality cannot be improved using the variance alone: for , the variable taking the values with probability each and otherwise has mean , variance and exactly.
Theorem— Theorem (weak law of large numbers)
Let be pairwise uncorrelated (for instance, independent) random variables with common mean and common finite variance , and let . Then for every ,
That is, converges in probability to .
Proof
By linearity, . By the variance-of-a-sum theorem and , . Chebyshev's inequality applied to with gives the bound, which tends to as for fixed .
∎
Does the coin remember?
The running proportion of heads wanders into the band 1/2 ± 1/√n and stays near 1/2. Run it several times: early on, the paths differ a lot.
- this run
- exact probability 1/2
- 1/2 ± 1/√n (about 95% of runs)
968 heads in 2,000 flips: proportion
Simulated0.484
Exact1/2 = 0.5
Simulation of 2,000 flips: 968 heads, proportion 0.484. The exact probability is 1/2.
Evidence, not proofThis is a simulation of 2,000 flips (run 1) using a seeded random number generator. It is evidence, not proof: the exact values come from mathematics, and a new run gives slightly different numbers.
The proportion settles down, but the difference between the number of heads and n/2 typically grows like √n: the law of large numbers is about proportions, not counts.
The law of large numbers works by swamping, not compensation. After ten heads in a row the coin is not "due" a tail; the next thousand flips simply dilute the early surplus. The number of excess heads typically grows like ; only the proportion settles.
How sharp is the bound? For fair coin flips and , Chebyshev gives , while the true value is about . Chebyshev uses only the variance, so it must cover the worst distribution with that variance; for bounded variables, Hoeffding's inequality (1963) gives the exponentially small bound . The second experiment below compares all of these with exact binomial tails.
Two stronger theorems, stated without proof:
- Khinchin's weak law (1929): for independent, identically distributed (i.i.d.) , finite mean alone suffices.
- The strong law of large numbers (Kolmogorov, 1933; Etemadi's 1981 proof needs only pairwise independence): if the are pairwise independent, identically distributed, with , then . The strong law says almost every individual sequence of averages converges; the weak law only says that, at each large , a deviation is unlikely. It is proved in Mathlib (see below).
The hypothesis matters: for i.i.d. Cauchy variables, has exactly the same Cauchy distribution as for every — averaging does not help at all. The law of large numbers is also the principle behind Monte Carlo integration: to estimate , average for independent uniform ; the error is of order , whatever the dimension.
The central limit theorem
The law of large numbers says . The fluctuations have size , so we magnify them by and ask about the shape of what we see.
Definition— convergence in distribution
Random variables converge in distribution to if at every where is continuous. When the limit is normal (which has a continuous distribution function), this means convergence at every .
Theorem— Theorem (central limit theorem, Lindeberg–Lévy)
Let be independent and identically distributed with mean and finite variance , and let . Then for every ,
Proof
A proof sketch under an extra hypothesis. Assume the moment generating function is finite for (this is stronger than finite variance). Put , so , , and as (Taylor's theorem; the moment generating function can be differentiated under the expectation inside its interval of convergence). The standardised sum is , and by independence the expectation of a product of the independent factors is the product of expectations:
which is the moment generating function of (complete the square in ). A continuity theorem (Curtiss, 1942) says that convergence of moment generating functions on a neighbourhood of implies convergence in distribution; we cite it without proof. The general theorem replaces by the characteristic function , which exists for every distribution, and uses Lévy's continuity theorem; that is the proof formalised in Mathlib.
∎
Example— The normal approximation in practice
fair coin flips: has mean and standard deviation . Since takes whole-number values, , and the continuity correction approximates this by ; the exact value is (without the correction one gets ). For the sum of dice (mean , variance ), , against an exact . And the germination promise in the motivation: seeds with give mean and standard deviation , so about of the time the count lies within of .
How fast? The Berry–Esseen theorem (1941–42) quantifies the convergence: if , then
where is a universal constant (known to satisfy , Shevtsova 2011). Skewed distributions, with large , need larger ; the third experiment measures this for a die and for a coin with .
What the theorem does not say.
- It does not say that data become normal. A sample of household incomes is as skewed as the population it came from; what is approximately normal is the distribution of the average (or sum) of many independent draws, across hypothetical repetitions.
- It needs finite variance. Averages of i.i.d. Cauchy variables are Cauchy for every , and heavy-tailed sums converge (when they converge at all) to other "stable" laws, with a different scaling than .
- It needs independence, or at least weak dependence. Sums of strongly dependent variables — the same measurement error repeated, contagion in financial losses — need not look normal.
- It controls absolute, not relative, error. Far in the tails, where is tiny, the normal approximation may be off by orders of magnitude; such "large deviation" probabilities need other tools (Cramér, 1938).
The theorem also explains why the normal distribution is everywhere: a measurement influenced by many small, roughly independent effects (genes and environment on height, many small errors in an astronomical observation) is approximately normal — a heuristic, valid exactly to the extent that its hypotheses are.
Probability in Lean and Mathlib
Mathlib builds probability on measure theory: a probability space is a measure μ with IsProbabilityMeasure μ, a random variable is a function X : Ω → ℝ, its expectation is the integral ∫ ω, X ω ∂μ (written μ[X]), its variance is Var[X; μ], and X ⟂ᵢ[μ] Y says that X and Y are independent. "Has finite variance" is MemLp X 2 μ. Mathlib's library has grown to include the strong law of large numbers and, recently, the central limit theorem, so this lesson can connect its whole arc to formal proofs.
Linearity and indicators. The expected number of events that occur is the sum of their probabilities, with no independence assumed; and the "fixed points of a shuffle" example, proved through Burnside's lemma (the total number of fixed points of a group action is the number of orbits times the size of the group — here there is one orbit):
/-- **Linearity of expectation for indicators.** For any events `A i` (`i ∈ s`), the expected
number of them that occur is the sum of their probabilities: `E[∑ 1_{A i}] = ∑ P(A i)`.
No independence is assumed. Proof: the integral of a finite sum is the sum of the integrals
(`integral_finsetSum`), and the integral of an indicator is the measure of the set
(`integral_indicator_one`). -/
theorem expectation_sum_indicators [IsProbabilityMeasure μ] {ι : Type*} (s : Finset ι)
(A : ι → Set Ω) (hA : ∀ i, MeasurableSet (A i)) :
∫ ω, (∑ i ∈ s, (A i).indicator (1 : Ω → ℝ) ω) ∂μ = ∑ i ∈ s, μ.real (A i) := by
rw [integral_finsetSum]
· exact sum_congr rfl fun i _ => integral_indicator_one (hA i)
· intro i _
exact (integrable_const (1 : ℝ)).indicator (hA i)/-- **A random permutation has, on average, exactly one fixed point.** Summing the number of
fixed points over all permutations of a non-empty finite set gives the number of permutations.
The lesson proves this with indicators and linearity of expectation; here it follows from
Mathlib's **Burnside lemma** (`MulAction.sum_card_fixedBy_eq_card_orbits_mul_card_group`:
the total number of fixed points is (number of orbits) × (size of the group)), because the
permutations of `α` move any point to any other, so there is exactly one orbit. -/
theorem perm_fixed_points_average (α : Type*) [Fintype α] [DecidableEq α] [Nonempty α] :
(∑ σ : Equiv.Perm α, Fintype.card (MulAction.fixedBy α σ)) =
Fintype.card (Equiv.Perm α) := by
classical
rw [MulAction.sum_card_fixedBy_eq_card_orbits_mul_card_group]
have h1 : Fintype.card (MulAction.orbitRel.Quotient (Equiv.Perm α) α) = 1 := by
rw [Fintype.card_eq_one_iff]
obtain ⟨a⟩ := ‹Nonempty α›
refine ⟨Quotient.mk _ a, fun q => ?_⟩
induction q using Quotient.inductionOn with
| h b =>
apply Quotient.sound
exact MulAction.exists_smul_eq (Equiv.Perm α) a b |>.imp fun g hg => hg
rw [h1, one_mul]Distributions. Mathlib has the binomial, geometric, Poisson, exponential and Gaussian distributions. We cite the binomial mean and the Gaussian mean and variance, prove the geometric mean from the differentiated geometric series exactly as in the lesson, prove the memoryless property from Mathlib's distribution function of the exponential law, and cite the Poisson limit theorem:
/-- **The binomial mean.** If `X` has the binomial distribution `Bin(n, p)`, then `E[X] = np`.
This is Mathlib's `ProbabilityTheory.integral_of_hasLaw_binomial`, proved there with the
identity `k·C(n, k) = n·C(n − 1, k − 1)` and the binomial theorem; the lesson's proof writes
`X` as a sum of `n` indicators instead. -/
theorem binomial_mean {n : ℕ} {p : unitInterval} {X : Ω → ℝ}
(hX : HasLaw X (Bin(ℝ, n, p)) μ) : μ[X] = (p : ℝ) * n :=
integral_of_hasLaw_binomial hX/-- **The geometric mean.** If each trial succeeds with probability `p ∈ (0, 1]`, the number
of trials up to and including the first success takes the value `k + 1` with probability
`p (1 − p)ᵏ`, and its expectation is `∑ (k + 1) p (1 − p)ᵏ = 1/p`. Proof, as in the lesson:
with `r = 1 − p`, `∑ k rᵏ = r/(1 − r)²` (Mathlib's `hasSum_coe_mul_geometric_of_norm_lt_one`,
"differentiate the geometric series") and `∑ rᵏ = 1/(1 − r)`, so
`∑ (k + 1) rᵏ = 1/(1 − r)² = 1/p²`; multiply by `p`. -/
theorem geometric_mean {p : ℝ} (hp0 : 0 < p) (hp1 : p ≤ 1) :
HasSum (fun k : ℕ => ((k : ℝ) + 1) * (p * (1 - p) ^ k)) (1 / p) := by
have hr : ‖1 - p‖ < 1 := by
rw [Real.norm_eq_abs, abs_lt]
constructor <;> linarith
have h1 := hasSum_coe_mul_geometric_of_norm_lt_one hr
have h2 := hasSum_geometric_of_norm_lt_one hr
have h3 := (h1.add h2).mul_left p
have hp : p ≠ 0 := hp0.ne'
convert h3 using 1
· funext k
ring
· simp only [sub_sub_cancel]
field_simp
ring/-- **The exponential distribution is memoryless.** For Mathlib's exponential distribution
`expMeasure r` with rate `r > 0`, the survival function `P(T > x) = 1 − F(x)` satisfies
`P(T > s + t) = P(T > s) · P(T > t)` for `s, t ≥ 0`; equivalently
`P(T > s + t | T > s) = P(T > t)`. Proof: Mathlib's `cdf_expMeasure_eq` gives
`1 − F(x) = e^{−rx}` for `x ≥ 0`, and `e^{−r(s + t)} = e^{−rs} e^{−rt}`. -/
theorem exponential_memoryless {r : ℝ} (hr : 0 < r) {s t : ℝ} (hs : 0 ≤ s) (ht : 0 ≤ t) :
1 - cdf (expMeasure r) (s + t) = (1 - cdf (expMeasure r) s) * (1 - cdf (expMeasure r) t) := by
simp only [cdf_expMeasure_eq hr, add_nonneg hs ht, hs, ht, ↓reduceIte, sub_sub_cancel]
rw [← Real.exp_add]
ring_nf/-- The normal distribution `N(m, v)` (Mathlib's `gaussianReal m v`) has mean `m`. This is
Mathlib's `ProbabilityTheory.integral_id_gaussianReal`. -/
theorem gaussian_mean (m : ℝ) (v : NNReal) : ∫ x, x ∂(gaussianReal m v) = m :=
integral_id_gaussianReal/-- The normal distribution `N(m, v)` has variance `v`. This is Mathlib's
`ProbabilityTheory.variance_id_gaussianReal`. -/
theorem gaussian_variance (m : ℝ) (v : NNReal) : Var[id; gaussianReal m v] = v :=
variance_id_gaussianReal/-- **Poisson limit theorem.** If `n · pₙ → λ`, then the binomial probabilities
`C(n, k) pₙᵏ (1 − pₙ)ⁿ⁻ᵏ` tend to the Poisson probability `e^{−λ} λᵏ / k!` for each fixed `k`.
This is Mathlib's `ProbabilityTheory.tendsto_choose_mul_pow_of_tendsto_mul_atTop`; the lesson
proves the case `pₙ = λ/n`. -/
theorem poisson_limit {p : ℕ → ℝ} {lam : ℝ} (k : ℕ)
(hp : Tendsto (fun n : ℕ => (n : ℝ) * p n) atTop (𝓝 lam)) :
Tendsto (fun n : ℕ => ((n.choose k : ℕ) : ℝ) * p n ^ k * (1 - p n) ^ (n - k)) atTop
(𝓝 (Real.exp (-lam) * lam ^ k / (k.factorial : ℝ))) :=
tendsto_choose_mul_pow_of_tendsto_mul_atTop k hpIndependence. The product rule and the additivity of variance, from Mathlib, and the uncorrelated-but-dependent example, computed in exact rational arithmetic (a three-point distribution needs no measure theory, so we average over Fin 3 directly):
/-- **Independent variables multiply in expectation:** if `X` and `Y` are independent then
`E[XY] = E[X] E[Y]`. This is Mathlib's `IndepFun.integral_fun_mul_eq_mul_integral`.
Without independence (or at least zero covariance) the formula fails: see
`uncorrelated_not_independent` and the lesson's example `X = Y` a fair coin. -/
theorem expectation_mul_indep {X Y : Ω → ℝ} (hXY : X ⟂ᵢ[μ] Y)
(hX : AEStronglyMeasurable X μ) (hY : AEStronglyMeasurable Y μ) :
∫ ω, X ω * Y ω ∂μ = (∫ ω, X ω ∂μ) * ∫ ω, Y ω ∂μ :=
hXY.integral_fun_mul_eq_mul_integral hX hY/-- **Variances of independent variables add:** `Var(X + Y) = Var X + Var Y` when `X ⟂ Y` and
both have finite variance. This is Mathlib's `ProbabilityTheory.IndepFun.variance_add`.
(Mathlib also has the general formula with the covariance term.) -/
theorem variance_add_indep {X Y : Ω → ℝ} (hX : MemLp X 2 μ) (hY : MemLp Y 2 μ)
(hXY : X ⟂ᵢ[μ] Y) : Var[X + Y; μ] = Var[X; μ] + Var[Y; μ] :=
hXY.variance_add hX hY/-- The average of a function on three equally likely outcomes `0, 1, 2`: the expectation for
the uniform distribution on `Fin 3`, computed exactly in `ℚ`. -/
def avg3 (f : Fin 3 → ℚ) : ℚ := (∑ i, f i) / 3/-- **Uncorrelated does not imply independent.** Let `X` be uniform on `{−1, 0, 1}` and
`Y = X²`. Then `E[XY] = E[X] E[Y]` (both sides are `0`), yet `X` and `Y` are dependent:
`P(X = 1 and Y = 0) = 0` while `P(X = 1) · P(Y = 0) = 1/3 · 1/3`. The probabilities of events
are averages of indicator functions. Checked by exact rational arithmetic. -/
theorem uncorrelated_not_independent :
let X : Fin 3 → ℚ := ![-1, 0, 1]
let Y : Fin 3 → ℚ := fun i => X i ^ 2
avg3 (fun i => X i * Y i) = avg3 X * avg3 Y ∧
avg3 (fun i => if X i = 1 ∧ Y i = 0 then 1 else 0) ≠
avg3 (fun i => if X i = 1 then 1 else 0) * avg3 (fun i => if Y i = 0 then 1 else 0) := by
simp only [avg3, Fin.sum_univ_three]
norm_numMarkov, Chebyshev and the weak law. Markov's inequality is cited from Mathlib. Chebyshev's inequality is then proved from it, line by line as in the human proof, and compared with Mathlib's own version (which states the probability as an extended non-negative real, hence the ENNReal.ofReal):
/-- **Markov's inequality:** for a non-negative integrable `f` and any `a`,
`a · P(f ≥ a) ≤ E[f]`. This is Mathlib's `mul_meas_ge_le_integral_of_nonneg`. (The measure
theory lesson proves the version for `[0, ∞]`-valued functions.) -/
theorem markov {f : Ω → ℝ} (hf : 0 ≤ᵐ[μ] f) (hint : Integrable f μ) (a : ℝ) :
a * μ.real {ω | a ≤ f ω} ≤ ∫ ω, f ω ∂μ :=
mul_meas_ge_le_integral_of_nonneg hf hint a/-- **Chebyshev's inequality**, proved from Markov's as in the lesson: for `X` with finite
variance and `c > 0`, `c² · P(|X − E X| ≥ c) ≤ Var X`. Proof: `|X − EX| ≥ c` happens exactly
when `(X − EX)² ≥ c²`; apply Markov's inequality to the non-negative variable `(X − EX)²`,
whose expectation is `Var X`. -/
theorem chebyshev [IsProbabilityMeasure μ] {X : Ω → ℝ} (hX : MemLp X 2 μ) {c : ℝ}
(hc : 0 < c) : c ^ 2 * μ.real {ω | c ≤ |X ω - μ[X]|} ≤ Var[X; μ] := by
set m := μ[X]
-- The events `{c ≤ |X − m|}` and `{c² ≤ (X − m)²}` are equal.
have hset : {ω | c ≤ |X ω - m|} = {ω | c ^ 2 ≤ (X ω - m) ^ 2} := by
ext ω
simp only [Set.mem_ofPred_eq]
rw [sq_le_sq, abs_of_pos hc]
-- `(X − m)²` is non-negative and integrable.
have hint : Integrable (fun ω => (X ω - m) ^ 2) μ :=
(hX.sub (memLp_const m)).integrable_sq
have hnn : 0 ≤ᵐ[μ] fun ω => (X ω - m) ^ 2 := Eventually.of_forall fun ω => sq_nonneg _
rw [hset, variance_eq_integral hX.aestronglyMeasurable.aemeasurable]
exact mul_meas_ge_le_integral_of_nonneg hnn hint (c ^ 2)/-- Mathlib's form of Chebyshev's inequality, `meas_ge_le_variance_div_sq`:
`P(|X − E X| ≥ c) ≤ Var X / c²`, with the probability as an extended non-negative real. -/
theorem chebyshev_library [IsFiniteMeasure μ] {X : Ω → ℝ} (hX : MemLp X 2 μ) {c : ℝ}
(hc : 0 < c) :
μ {ω | c ≤ |X ω - μ[X]|} ≤ ENNReal.ofReal (Var[X; μ] / c ^ 2) :=
meas_ge_le_variance_div_sq hX hcThe weak law of large numbers with its explicit rate , and the limit statement. The hypotheses are exactly those of the lesson's theorem with "pairwise uncorrelated" strengthened to "pairwise independent", which is what Mathlib's IndepFun.variance_sum uses:
/-- **The weak law of large numbers, with a rate.** Let `X₀, X₁, …` be pairwise independent,
with finite variance, all with mean `m` and variance `v`. For `n ≥ 1` and `ε > 0`, the sample
mean `X̄ₙ = (X₀ + ⋯ + Xₙ₋₁)/n` satisfies `ε² · P(|X̄ₙ − m| ≥ ε) ≤ v / n`.
Proof, as in the lesson: `E[X̄ₙ] = m` by linearity; `Var X̄ₙ = (1/n²) · n v = v/n` because
variances of pairwise independent variables add (`IndepFun.variance_sum`) and
`Var(cX) = c² Var X`; then apply `chebyshev`. -/
theorem weak_law_bound [IsProbabilityMeasure μ] {X : ℕ → Ω → ℝ} {m v : ℝ}
(hL2 : ∀ i, MemLp (X i) 2 μ) (hindep : Pairwise fun i j => X i ⟂ᵢ[μ] X j)
(hmean : ∀ i, μ[X i] = m) (hvar : ∀ i, Var[X i; μ] = v) {n : ℕ} (hn : 0 < n) {ε : ℝ}
(hε : 0 < ε) :
ε ^ 2 * μ.real {ω | ε ≤ |(n : ℝ)⁻¹ * ∑ i ∈ range n, X i ω - m|} ≤ v / n := by
set S : Ω → ℝ := fun ω => (n : ℝ)⁻¹ * ∑ i ∈ range n, X i ω with hS
have hnR : (n : ℝ) ≠ 0 := Nat.cast_ne_zero.mpr hn.ne'
-- The sample mean has finite variance.
have hsum : MemLp (∑ i ∈ range n, X i) 2 μ := memLp_finsetSum' _ fun i _ => hL2 i
have hSL2 : MemLp S 2 μ := by
have := hsum.const_mul ((n : ℝ)⁻¹)
convert this using 1
funext ω
simp [hS, Finset.sum_apply]
-- Its expectation is `m` (linearity of expectation).
have hES : μ[S] = m := by
simp only [hS]
rw [integral_const_mul, integral_finsetSum _ fun i _ => (hL2 i).integrable one_le_two]
simp only [hmean, sum_const, card_range, nsmul_eq_mul]
field_simp
-- Its variance is `v / n`.
have hVS : Var[S; μ] = v / n := by
have hS' : S = fun ω => (n : ℝ)⁻¹ * (∑ i ∈ range n, X i) ω := by
funext ω
simp [hS, Finset.sum_apply]
rw [hS', variance_const_mul,
IndepFun.variance_sum (fun i _ => hL2 i) (fun i _ j _ hij => hindep hij)]
simp only [hvar, sum_const, card_range, nsmul_eq_mul]
field_simp
have key := chebyshev hSL2 hε
rw [hES, hVS] at key
exact key/-- **The weak law of large numbers.** Under the hypotheses of `weak_law_bound`, for every
`ε > 0`, `P(|X̄ₙ − m| ≥ ε) → 0` as `n → ∞`: the sample mean converges in probability to the
mean. Proof: the probability lies between `0` and `v / (n ε²)`, which tends to `0`. -/
theorem weak_law [IsProbabilityMeasure μ] {X : ℕ → Ω → ℝ} {m v : ℝ}
(hL2 : ∀ i, MemLp (X i) 2 μ) (hindep : Pairwise fun i j => X i ⟂ᵢ[μ] X j)
(hmean : ∀ i, μ[X i] = m) (hvar : ∀ i, Var[X i; μ] = v) {ε : ℝ} (hε : 0 < ε) :
Tendsto (fun n : ℕ => μ.real {ω | ε ≤ |(n : ℝ)⁻¹ * ∑ i ∈ range n, X i ω - m|}) atTop
(𝓝 0) := by
have hε2 : 0 < ε ^ 2 := by positivity
-- Upper bound `v / ε² · (1 / n)`, which tends to `0`.
have hup : Tendsto (fun n : ℕ => v / ε ^ 2 * (1 / (n : ℝ))) atTop (𝓝 0) := by
simpa using tendsto_one_div_atTop_nhds_zero_nat.const_mul (v / ε ^ 2)
refine tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds hup ?_ ?_
· exact Eventually.of_forall fun n => measureReal_nonneg
· filter_upwards [eventually_gt_atTop 0] with n hn
have h := weak_law_bound hL2 hindep hmean hvar hn hε
set P := μ.real {ω | ε ≤ |(n : ℝ)⁻¹ * ∑ i ∈ range n, X i ω - m|}
calc P = ε ^ 2 * P / ε ^ 2 := by field_simp
_ ≤ v / n / ε ^ 2 := div_le_div_of_nonneg_right h hε2.le
_ = v / ε ^ 2 * (1 / (n : ℝ)) := by ringThe great limit theorems. The strong law (Mathlib follows Etemadi's proof, so it needs only pairwise independence and a finite mean) and the central limit theorem, in its standardised form:
/-- **The strong law of large numbers** (Kolmogorov; Etemadi's 1981 proof, which needs only
pairwise independence). If `X₀, X₁, …` are pairwise independent, identically distributed and
integrable, then almost surely `X̄ₙ → E[X₀]`. This is Mathlib's
`ProbabilityTheory.strong_law_ae`. Note that no finite variance is needed. -/
theorem strong_law [IsProbabilityMeasure μ] (X : ℕ → Ω → ℝ) (hint : Integrable (X 0) μ)
(hindep : Pairwise fun i j => X i ⟂ᵢ[μ] X j)
(hident : ∀ i, IdentDistrib (X i) (X 0) μ μ) :
∀ᵐ ω ∂μ, Tendsto (fun n : ℕ => (n : ℝ)⁻¹ * ∑ i ∈ range n, X i ω) atTop (𝓝 μ[X 0]) := by
simpa [smul_eq_mul] using strong_law_ae X hint hindep hident/-- **The central limit theorem** (Lindeberg–Lévy form, standardised). If `X₀, X₁, …` are
independent and identically distributed with mean `0` and variance `1`, then
`(X₀ + ⋯ + Xₙ₋₁)/√n` converges in distribution to a standard normal variable `Y`. This is
Mathlib's `ProbabilityTheory.tendstoInDistribution_inv_sqrt_mul_sum`, proved with
characteristic functions and Lévy's continuity theorem, as sketched in the lesson. The general
case (mean `μ`, variance `σ² > 0`) follows by standardising `(Xᵢ − μ)/σ`. -/
theorem clt {Ω' : Type*} {mΩ' : MeasurableSpace Ω'} {P' : Measure Ω'} [IsProbabilityMeasure μ]
[IsProbabilityMeasure P'] {X : ℕ → Ω → ℝ} {Y : Ω' → ℝ}
(hY : HasLaw Y (gaussianReal 0 1) P') (h0 : μ[X 0] = 0) (h1 : μ[X 0 ^ 2] = 1)
(hindep : iIndepFun X μ) (hident : ∀ i, IdentDistrib (X i) (X 0) μ μ) :
TendstoInDistribution (fun (n : ℕ) ω => (Real.sqrt n)⁻¹ * ∑ k ∈ range n, X k ω) atTop Y
(fun _ => μ) P' :=
tendstoInDistribution_inv_sqrt_mul_sum hY h0 h1 hindep hidentWhat is and is not formalised. Proved here (independent): linearity of expectation for indicators, the average number of fixed points, the geometric mean, the memoryless property, the uncorrelated-but-dependent example, Chebyshev's inequality from Markov's, and the weak law with rate. Cited from Mathlib: Markov's inequality, the product rule, additivity of variance, the binomial mean, the Gaussian moments, the Poisson limit theorem, the strong law and the central limit theorem. Not formalised here: the variance of the number of fixed points, the coupon-collector formula, the Berry–Esseen theorem (not in Mathlib at the time of writing) and the normal-approximation numbers, which are numerical.
Exhaustive checks, exact tails and the speed of the CLT
First, linearity of expectation in action: every permutation of up to seven objects, with the exact mean and variance of the number of fixed points, the chance of a derangement (which tends to ) and the whole distribution, which is close to Poisson.
"""Fixed points of random permutations: linearity of expectation, checked exhaustively.
Shuffle n cards labelled 1..n. The number of cards that end up in their own
place is a sum of n dependent indicator variables, each with expectation 1/n,
so linearity of expectation gives mean 1 for every n - no independence needed.
A covariance calculation gives variance 1 for n >= 2. Here we list all n!
permutations for n <= 7 and compute these numbers exactly, together with the
chance of no fixed point (a derangement), which tends to 1/e, and the whole
distribution for n = 7, which is close to Poisson(1).
"""
import itertools
import math
from fractions import Fraction
def fixed_point_counts(n):
"""List of the number of fixed points of each permutation of range(n)."""
if n < 0:
raise ValueError("n must be non-negative")
return [sum(1 for i, j in enumerate(p) if i == j)
for p in itertools.permutations(range(n))]
def mean_and_variance(values):
"""Exact mean and variance (Fractions) of equally likely values."""
if not values:
raise ValueError("need at least one value")
m = Fraction(sum(values), len(values))
v = Fraction(sum(x * x for x in values), len(values)) - m * m
return m, v
def distribution(values):
"""Dictionary k -> exact probability that the count equals k."""
total = len(values)
return {k: Fraction(values.count(k), total) for k in sorted(set(values))}
def main():
print(" n n! mean variance P(no fixed point) vs 1/e = 0.367879")
for n in range(1, 8):
counts = fixed_point_counts(n)
m, v = mean_and_variance(counts)
p0 = distribution(counts).get(0, Fraction(0))
print(f"{n:>2} {len(counts):>7} {str(m):>5} {str(v):>9}"
f" {str(p0):>14} = {float(p0):.6f}")
print()
print("Distribution of the number of fixed points for n = 7:")
dist = distribution(fixed_point_counts(7))
print(" k exact probability Poisson(1): e^-1/k!")
for k in range(8):
p = dist.get(k, Fraction(0))
poisson = math.exp(-1) / math.factorial(k)
print(f" {k} {float(p):>17.6f} {poisson:>19.6f}")
print()
print("Epistemic status: exhaustive and exact for n = 1, ..., 7 (5913")
print("permutations in all). That the mean is 1 and the variance 1 for")
print("every n >= 2 is proved in the lesson with indicators; the limit")
print("1/e and the Poisson(1) limit are theorems that this table only")
print("illustrates.")
if __name__ == "__main__":
main()Next, how good is Chebyshev's inequality? For fair coins we compute the exact tail probabilities of the weak law and compare them with Chebyshev's bound, Hoeffding's bound and the normal approximation — and then verify exactly that a three-point distribution attains Chebyshev's bound.
"""How good is Chebyshev's inequality? Exact coin-flip tails against three estimates.
For n fair coin flips with S heads, the weak law of large numbers says that
P(|S/n - 1/2| >= eps) -> 0. We compute this probability exactly (integer
arithmetic on binomial coefficients) and compare it with Chebyshev's bound
1/(4 n eps^2), Hoeffding's bound 2 exp(-2 n eps^2) and the normal
approximation with a continuity correction. Then we check exactly that
Chebyshev's inequality cannot be improved in general: a three-point
distribution attains it.
"""
import math
from fractions import Fraction
def tail_probability(n, eps):
"""Exact P(|S/n - 1/2| >= eps) for S ~ Binomial(n, 1/2), as a Fraction.
``eps`` may be a Fraction, an int or a decimal string such as "0.05".
"""
if n < 1:
raise ValueError("n must be positive")
eps = Fraction(eps)
total = 0
coefficient = 1 # C(n, k), updated incrementally
for k in range(n + 1):
if abs(Fraction(k, n) - Fraction(1, 2)) >= eps:
total += coefficient
coefficient = coefficient * (n - k) // (k + 1)
return Fraction(total, 2 ** n)
def chebyshev_bound(n, eps):
"""Chebyshev: Var(S/n) / eps^2 = 1 / (4 n eps^2)."""
return 1 / (4 * n * float(eps) ** 2)
def hoeffding_bound(n, eps):
"""Hoeffding (1963) for variables in [0, 1]: 2 exp(-2 n eps^2)."""
return 2 * math.exp(-2 * n * float(eps) ** 2)
def normal_approximation(n, eps):
"""2 (1 - Phi(z)) with z = (c - 1/2) / (sqrt(n)/2), c = ceil(n eps).
For even n the deviation |S - n/2| is a whole number, so the event is
|S - n/2| >= c, and the continuity correction moves c to c - 1/2.
"""
c = math.ceil(n * Fraction(eps))
z = (c - 0.5) / (math.sqrt(n) / 2)
return math.erfc(z / math.sqrt(2))
def three_point_check(k):
"""X = -k, 0, k with probabilities 1/(2k^2), 1 - 1/k^2, 1/(2k^2).
Returns (variance, P(|X| >= k), Chebyshev bound 1/k^2), all exact. Here
the mean is 0 and the standard deviation 1, so the bound is attained.
"""
k = Fraction(k)
if k < 1:
raise ValueError("k must be at least 1")
p = 1 / (2 * k * k)
variance = 2 * p * k * k
return variance, 2 * p, 1 / (k * k)
def main():
eps = Fraction(1, 20)
print("Fair coin, eps = 0.05: P(|S/n - 1/2| >= eps), exact and estimated")
print(f"{'n':>6} {'exact':>11} {'Chebyshev':>11} {'Hoeffding':>11}"
f" {'normal':>11}")
for n in [10, 100, 1000, 10000]:
exact = float(tail_probability(n, eps))
print(f"{n:>6} {exact:>11.3e} {chebyshev_bound(n, eps):>11.3e}"
f" {hoeffding_bound(n, eps):>11.3e}"
f" {normal_approximation(n, eps):>11.3e}")
print()
print("Chebyshev only uses the variance. It is valid for every n, but for")
print("coins the true tail falls exponentially fast (like Hoeffding's")
print("bound), not like 1/n. Values above 1 are true but useless.")
print()
print("Yet Chebyshev cannot be improved without more information:")
for k in [2, 3, 10]:
variance, prob, bound = three_point_check(k)
print(f" X = -{k}, 0, {k}: Var X = {variance}, P(|X| >= {k}) = {prob},"
f" bound 1/k^2 = {bound}")
print()
print("Epistemic status: the coin tails are exact rational numbers (shown")
print("rounded); the Hoeffding and normal columns are floating-point values")
print("of formulas. The table illustrates the theorems for four values of")
print("n; it does not prove them. The three-point rows are exact and show")
print("the bound is attained, so no better constant works for all")
print("distributions with given variance.")
if __name__ == "__main__":
main()Finally, how fast does the central limit theorem take hold? The exact distribution of a sum of dice or of lopsided coins is computed by repeated convolution, and its largest gap from the normal distribution function is compared with the Berry–Esseen bound.
"""How fast does the central limit theorem kick in? Exact sums versus the bell curve.
For a fair die and for a lopsided coin (heads with probability 0.1) we compute
the exact distribution of the sum S_n of n independent copies by repeated
convolution, standardise it, and measure the Kolmogorov distance
D_n = sup_x |P((S_n - n mu)/(sigma sqrt n) <= x) - Phi(x)|. The CLT says
D_n -> 0; the Berry-Esseen theorem says D_n <= C rho / (sigma^3 sqrt n) with
C <= 0.4748 (Shevtsova 2011), where rho = E|X - mu|^3. The skewed coin
converges visibly more slowly.
"""
import math
import numpy as np
C_BERRY_ESSEEN = 0.4748
def sum_distribution(pmf, n):
"""Probabilities of S_n = 0, 1, ... for n i.i.d. copies of ``pmf``.
``pmf`` lists P(X = 0), P(X = 1), ...; the result is the n-fold
convolution, computed by repeated squaring.
"""
if n < 1:
raise ValueError("n must be positive")
result = np.array([1.0])
power = np.asarray(pmf, dtype=float)
while n:
if n & 1:
result = np.convolve(result, power)
n >>= 1
if n:
power = np.convolve(power, power)
return result
def moments(pmf):
"""Mean, standard deviation and third absolute central moment of pmf."""
values = np.arange(len(pmf))
pmf = np.asarray(pmf, dtype=float)
mu = float(values @ pmf)
sigma = math.sqrt(float(((values - mu) ** 2) @ pmf))
rho = float((np.abs(values - mu) ** 3) @ pmf)
return mu, sigma, rho
def phi(z):
"""Standard normal distribution function."""
return 0.5 * math.erfc(-z / math.sqrt(2))
def kolmogorov_distance(pmf, n):
"""sup_x |F_n(x) - Phi(x)| for the standardised sum of n copies of pmf.
F_n is a step function, so the supremum is attained at a jump: compare
Phi there with the values of F_n just before and just after the jump.
"""
mu, sigma, _ = moments(pmf)
probs = sum_distribution(pmf, n)
cdf = np.cumsum(probs)
worst = 0.0
below = 0.0
for k in range(len(probs)):
if probs[k] == 0.0:
continue
p = phi((k - n * mu) / (sigma * math.sqrt(n)))
worst = max(worst, abs(p - below), abs(p - cdf[k]))
below = cdf[k]
return worst
def berry_esseen_bound(pmf, n):
"""C rho / (sigma^3 sqrt n)."""
_, sigma, rho = moments(pmf)
return C_BERRY_ESSEEN * rho / (sigma ** 3 * math.sqrt(n))
def main():
die = [0] + [1 / 6] * 6
coin = [0.9, 0.1]
print("Kolmogorov distance D_n between the standardised sum and N(0, 1)")
print(f"{'n':>5} | {'die D_n':>9} {'sqrt(n) D_n':>12} {'B-E bound':>10} |"
f" {'coin D_n':>9} {'sqrt(n) D_n':>12} {'B-E bound':>10}")
for n in [1, 4, 16, 64, 256]:
row = [f"{n:>5} |"]
for pmf in (die, coin):
d = kolmogorov_distance(pmf, n)
row.append(f"{d:>9.4f} {math.sqrt(n) * d:>12.3f}"
f" {berry_esseen_bound(pmf, n):>10.4f}")
print(" ".join([row[0], row[1], "|", row[2]]))
print()
print("sqrt(n) D_n stays roughly constant: the error falls like 1/sqrt(n),")
print("as Berry-Esseen predicts, and every D_n is below its bound. The")
print("skewed coin (rho / sigma^3 = 2.73 versus 1.28 for the die) needs")
print("many more terms before the bell curve is a good description.")
print()
print("Epistemic status: the distributions of S_n are exact up to")
print("floating-point rounding (about 1e-15), so the distances are reliable")
print("numerical values. They illustrate the CLT and the Berry-Esseen")
print("theorem for five values of n and two distributions; they do not")
print("prove either theorem (the CLT is proved in Mathlib, see the lesson).")
if __name__ == "__main__":
main()The first experiment is exhaustive for finitely many and exact; the second computes exact probabilities and floating-point bounds; the third is numerical (exact distributions, floating-point arithmetic). None of them proves a theorem for all — that is the job of the proofs above and of the Lean module.
Explore: sums and square roots
Sums of independent pieces
Two dice: the triangle is the first step towards the bell. Random walk: the root-mean-square distance after n steps is exactly √n.
- simulated frequency
- exact (ways out of 36)
Sum 7
Simulated16.3%
Exact6/36 ≈ 16.7%
Sum 12
Simulated3%
Exact1/36 ≈ 2.8%
Simulation of 2,000 rolls of two dice: a sum of 7 came up 16.3% of the time. The exact probability is 6/36, about 16.7%.
Evidence, not proofThis is a simulation of 2,000 rolls of two dice (run 1) using a seeded random number generator. It is evidence, not proof: the exact values come from mathematics, and a new run gives slightly different numbers.
There are 6 ways to make 7 (1+6, 2+5, 3+4, 4+3, 5+2, 6+1) but only one way to make 12 (6+6).
Try this:
- In two dice, the sum's distribution is the convolution of two uniform distributions: a triangle. Imagine adding a third die (a piecewise-quadratic shape), a fourth… the third experiment above shows how quickly the shape approaches the normal curve.
- In random walk, a walker takes steps of . The position has mean and variance (variances of independent steps add), so its typical size is , not : after steps, about from the start. Increase and check the curve. Dividing by gives the law of large numbers; dividing by gives the central limit theorem.
Exercises
1. Probability theory
Warm-upHumanYou roll a fair die until the first six appears. What is the expected number of rolls, including the roll that shows the six?
2. Probability theory
CoreHumanA fair coin is flipped times. A double is a position () where flips and are both heads; overlapping doubles count separately (HHH contains two). What is the expected number of doubles?
3. Probability theory
CoreHumanIn which of these situations is guaranteed? (All variables have finite variance. Choose all that apply.)
4. Probability theory
CoreHumanLet be the number of heads in flips of a fair coin. What is the smallest for which Chebyshev's inequality guarantees ?
5. Probability theory
CoreHumanThe proof of the weak law of large numbers has four steps: (1) ; (2) ; (3) apply Chebyshev's inequality to ; (4) let . Which step uses the hypothesis that the are pairwise uncorrelated?
6. Probability theory
CoreHumanWhich statement is a correct consequence of the central limit theorem?
7. Probability theory
StretchHumanTen letters are put into ten addressed envelopes uniformly at random. Let be the number of letters in the right envelope. What is ?
8. Probability theory
CoreFormalWhich Lean statement correctly formalises Chebyshev's inequality ? (Here μ is a probability measure, μ[X] is and Var[X; μ] is .)
9. Probability theory
StretchComputationalWrite tail(n, k) returning the exact probability, as a Fraction, that the number of heads in fair coin flips satisfies . Then write chebyshev(n, k) returning Chebyshev's bound as a Fraction. The tests check that the bound always holds and is far from sharp for large .
Common misconceptions
Misconception
" always." This holds exactly when and are uncorrelated; independence is the usual sufficient condition. For , but . Contrast linearity, , which needs no hypothesis at all beyond finite expectations.
Misconception
"The central limit theorem says the data become normally distributed." It says that the distribution of a standardised sum or average of many independent observations is close to normal. The observations themselves keep their own distribution: a large sample of waiting times is still exponential-looking, and its histogram converges to the exponential density, not to a bell.
Misconception
"Uncorrelated means independent." Zero covariance rules out only linear dependence. With uniform on and , is completely determined by , yet . (For jointly normal variables, uncorrelated does imply independent — a special property of the normal family.)
Misconception
"After a run of heads, tails is due." Independent flips have no memory, and the law of large numbers does not work by compensation. The proportion of heads converges to because later flips swamp the early ones, while the excess number of heads typically grows like .
Misconception
"Every distribution has a mean; a symmetric one has mean at its centre." The Cauchy distribution is symmetric about but has no expectation, and the average of Cauchy observations is no more concentrated than one observation. Expectations require absolute convergence, and the limit theorems require their moment hypotheses.
Misconception
"Variances add, so ." For independent (or uncorrelated) and , : subtracting an independent noisy quantity adds noise. And without that hypothesis, the covariance term appears.
Many ways of seeing
Geometry— Random variables as vectors: covariance is an inner product
Random variables with finite variance form a vector space , and is an inner product on it (after identifying variables that agree with probability ). On centred variables the geometry is statistical: is a squared length, is an inner product, the correlation is the cosine of the angle between and , and is the Cauchy–Schwarz inequality. "Uncorrelated" means orthogonal, and for uncorrelated variables is Pythagoras' theorem. The expectation itself is the orthogonal projection of onto the line of constants — the constant minimising — and conditional expectation is projection onto a larger subspace. This picture underlies least squares in statistical inference.
Analysis— Expectation is an integral; the CLT is Fourier analysis
Kolmogorov's insight was that is the Lebesgue integral , so every theorem of measure theory — monotone and dominated convergence, Fubini — becomes a theorem of probability. The distribution of a sum of independent variables is the convolution of their distributions, and the characteristic function is the Fourier transform of the distribution, which turns convolution into multiplication: . The central limit theorem then says that — and is, up to scaling, its own Fourier transform. Seen this way, the normal law is a fixed point of "add two independent copies and rescale by ", and the CLT says this fixed point attracts every distribution with finite variance. Distributions with infinite variance can be attracted to other fixed points, the stable laws (Lévy, 1920s).
Algebra— Generating functions and counting fixed points by symmetry
For a random variable with values in , the probability generating function packages the distribution as a power series; independence turns sums into products, , so the binomial is and moments come from derivatives at (). The average number of fixed points has a group-theoretic meaning too: for any finite group acting on a finite set, Burnside's lemma says that the average number of points fixed by a random element of equals the number of orbits. The symmetric group acting on has one orbit, so a random permutation fixes one point on average — the formal proof in this lesson goes exactly this way. See groups.
Physics— Diffusion, Brownian motion and the bell curve in nature
A pollen grain in water is pushed by a huge number of independent molecular collisions. Einstein (1905) and Smoluchowski (1906) modelled its displacement as a sum of many small independent steps, so by the central limit theorem it is normally distributed with variance proportional to time — the law of diffusion, the continuous version of the random walk's . Jean Perrin's measurements of this spread (1908) gave one of the first accurate values of Avogadro's number, persuading sceptics that atoms exist. The density of the displacement solves the heat equation , whose fundamental solution is a Gaussian. In statistical mechanics, the law of large numbers is why macroscopic quantities such as pressure, an average over molecules, are effectively deterministic. (These are physical models: the mathematics proves what follows from the independence assumptions, not that nature satisfies them exactly.) See stochastic processes.
Set theory— Kolmogorov's axioms: a probability space is a measure space
In set-theoretic terms, events are subsets of , "and", "or" and "not" are intersection, union and complement, and a random variable is a function with — a measurable function. Its distribution is the pushforward measure on . The insistence on a σ-algebra rather than all subsets is forced: by Vitali's construction (which uses the axiom of choice), there is no countably additive, translation-invariant probability defined on every subset of . Kolmogorov's 1933 axioms resolved a century of foundational unease by making probability a branch of measure theory, while leaving open what probability means (frequencies, degrees of belief, propensities) — a question for statistics and philosophy rather than for the axioms.
Category theory— Probability as a monad
Measurable spaces with Markov kernels (measurable families of probability distributions ) as morphisms form a category: kernels compose by "first sample from , then from ", exactly as stochastic matrices multiply. Giry (1982) showed that the assignment , the space of probability measures on , is a monad whose Kleisli category is this category of kernels; the functor sends a measurable map to pushforward, so the distribution of a random variable is applied to . Mathlib contains the Giry monad (MeasureTheory.Measure.join and bind, packaged categorically in MeasCat.Giry) and composes kernels (ProbabilityTheory.Kernel) in exactly this way; the Markov chains lesson is its simplest instance.
History and global context
- Counting before probability. The combinatorics underlying discrete probability is older than probability itself: rules for counting combinations appear in Indian mathematics (Piṅgala's prosody; Bhāskara II's Līlāvatī, 12th century), in the work of Ibn Munʿim in 13th-century Marrakesh, and in the triangle of binomial coefficients described by Yang Hui in 1261 (after Jia Xian). In 9th-century Baghdad, al-Kindī used the frequencies of letters to break ciphers, an early piece of statistical reasoning.
- Games of chance. Gerolamo Cardano's Liber de ludo aleae (written in the 16th century, published 1663) computed odds for dice. The correspondence of Blaise Pascal and Pierre de Fermat in 1654 solved the "problem of points" (how to divide the stakes of an interrupted game), and Christiaan Huygens' De ratiociniis in ludo aleae (1657) made expectation the central notion.
- Limit theorems. Jacob Bernoulli's Ars Conjectandi (1713, published after his death) proved the first law of large numbers for repeated trials. Abraham de Moivre (1733; The Doctrine of Chances, 1738) found the normal approximation to the binomial with , and Pierre-Simon Laplace (Théorie analytique des probabilités, 1812) generalised it; Carl Friedrich Gauss (1809) derived the normal law of errors for least squares. Siméon Denis Poisson (1837) introduced the distribution named after him.
- The Russian school. Irénée-Jules Bienaymé (1853) and Pafnuty Chebyshev (1867) proved the inequality now called Chebyshev's, and Chebyshev used it for a general law of large numbers. His students Andrei Markov and Aleksandr Lyapunov continued the work: Lyapunov gave the first rigorous general proof of the central limit theorem (1900–01) using characteristic functions, and Markov extended the limit theorems to dependent sequences — the origin of Markov chains. Jarl Waldemar Lindeberg (1922) and Paul Lévy completed the classical picture; William Feller's two volumes (1950, 1966) made it a modern subject.
- Foundations. Andrei Kolmogorov's Grundbegriffe der Wahrscheinlichkeitsrechnung (1933) set probability on measure-theoretic axioms; Aleksandr Khinchin, Kolmogorov and Lévy proved the strong limit theorems; Nasrollah Etemadi (1981) gave the elementary proof of the strong law used in Mathlib. Andrew Berry (1941) and Carl-Gustav Esseen (1942) independently found the rate of convergence in the central limit theorem.
Further reading
- Geoffrey Grimmett and David Stirzaker, Probability and Random Processes (4th edition, 2020) — a complete undergraduate course, from these foundations to Markov chains and martingales; with its companion One Thousand Exercises in Probability.
- William Feller, An Introduction to Probability Theory and Its Applications, Volume I (1950; 3rd edition 1968) — the classic, rich in examples (coupon collecting, random walks, the Poisson approximation).
- Joseph K. Blitzstein and Jessica Hwang, Introduction to Probability (2nd edition, 2019) — a friendly first course built around stories and indicator variables.
- Sheldon Ross, A First Course in Probability (many editions since 1976) — a gentle, example-driven introduction.
- David Williams, Probability with Martingales (1991) — the measure-theoretic sequel, including a proof of the strong law.
- Rick Durrett, Probability: Theory and Examples (5th edition, 2019) — the graduate treatment of the limit theorems, including the characteristic-function proof of the central limit theorem.