Skip to content
The Lumenary
Early undergraduateUndergraduate (first or second year) 120 min

Probability theory

Single outcomes are unpredictable, yet averages settle down and their fluctuations take the shape of a bell — random variables, expectation and variance, and the two great limit theorems that explain why.

Formally verified · 19 LeanComputationally tested · 3 PythonAI-drafted · awaiting human reviewMathematically reviewed: Awaiting human review
MotivationH

Unpredictable outcomes, predictable averages

A seed cooperative in western Kenya tests a new maize variety: each seed germinates with probability about 0.90.9, and nobody can say which seeds will fail. Yet of 10 00010\,000 seeds, the cooperative can promise that between roughly 8 9408\,940 and 9 0609\,060 will germinate, and be right about 9595 times in 100100. 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.

IntuitionH

The Galton board

Drop a ball through nn rows of pins. At each pin it bounces left or right with probability 12\tfrac12, independently. Its final slot is the number SnS_n of rightward bounces, a sum of nn 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.

0123456789101112number of bounces to the right
  • 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:

  1. The balls pile up around the middle, n/2n/2: the expectation of SnS_n is n/2n/2.
  2. The width of the pile grows, but only like n\sqrt n: the standard deviation of SnS_n is n/2\sqrt n/2. So the proportion Sn/nS_n/n of right bounces has spread 1/(2n)1/(2\sqrt n), which shrinks: this is the law of large numbers.
  3. The pile has a characteristic bell shape, whatever the details: this is the central limit theorem.
DefinitionsH

Random variables and their distributions

Definition— probability space

A probability space (Ω,F,P)(\Omega, \mathcal F, P) consists of a set Ω\Omega of outcomes, a collection F\mathcal F of subsets of Ω\Omega called events (closed under complements and countable unions, and containing Ω\Omega), and a function P:F→[0,1]P : \mathcal F \to [0, 1] with P(Ω)=1P(\Omega) = 1 that is countably additive: P(⋃iAi)=∑iP(Ai)P\big(\bigcup_i A_i\big) = \sum_i P(A_i) for pairwise disjoint events A1,A2,…A_1, A_2, \dots (Kolmogorov's axioms).

When Ω\Omega is countable we may take every subset to be an event. For continuous models (a uniformly random point of [0,1][0, 1], 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 X:Ω→RX : \Omega \to \R such that {X≤x}={ω:X(ω)≤x}\{X \le x\} = \{\omega : X(\omega) \le x\} is an event for every x∈Rx \in \R. Its distribution (or law) is the probability measure B↦P(X∈B)B \mapsto P(X \in B) on R\R, and its distribution function is FX(x)=P(X≤x)F_X(x) = P(X \le x). Every distribution function is non-decreasing and right-continuous, with FX(x)→0F_X(x) \to 0 as x→−∞x \to -\infty and FX(x)→1F_X(x) \to 1 as x→∞x \to \infty, and it determines the distribution.

Two kinds of distribution cover most examples:

  • XX is discrete if it takes values in a countable set {x1,x2,… }\{x_1, x_2, \dots\}; its probability mass function is p(x)=P(X=x)p(x) = P(X = x), with ∑ip(xi)=1\sum_i p(x_i) = 1.
  • XX is continuous with density ff if f≥0f \ge 0 and P(a≤X≤b)=∫abf(x) dxP(a \le X \le b) = \int_a^b f(x)\,dx for all a≤ba \le b; then ∫−∞∞f=1\int_{-\infty}^\infty f = 1, FX′=fF_X' = f wherever ff is continuous, and P(X=x)=0P(X = x) = 0 for every single xx.

Definition— expectation and variance

The expectation (mean) of XX is

E[X]=∑ixi p(xi)(discrete),E[X]=∫−∞∞xf(x) dx(density),E[X] = \sum_i x_i\, p(x_i) \quad \text{(discrete)}, \qquad E[X] = \int_{-\infty}^{\infty} x f(x)\,dx \quad \text{(density)},

defined only when the sum or integral converges absolutely: ∑i∣xi∣ p(xi)<∞\sum_i |x_i|\,p(x_i) < \infty, resp. ∫∣x∣f(x) dx<∞\int |x| f(x)\,dx < \infty. More generally, for a function gg, E[g(X)]=∑ig(xi) p(xi)E[g(X)] = \sum_i g(x_i)\,p(x_i) or ∫g(x)f(x) dx\int g(x) f(x)\,dx (the "law of the unconscious statistician"), again when absolutely convergent. If μ=E[X]\mu = E[X] exists, the variance is Var⁡X=E[(X−μ)2]∈[0,∞]\operatorname{Var} X = E[(X - \mu)^2] \in [0, \infty] and the standard deviation is σ=Var⁡X\sigma = \sqrt{\operatorname{Var} X}.

Expanding the square and using linearity (proved below) gives the computing formula Var⁡X=E[X2]−(E[X])2\operatorname{Var} X = E[X^2] - (E[X])^2, and also Var⁡(aX+b)=a2Var⁡X\operatorname{Var}(aX + b) = a^2 \operatorname{Var} X: shifting does not change spread, and scaling by aa scales the standard deviation by ∣a∣|a|.

Definition— joint distribution, independence, covariance

Random variables X,YX, Y on the same space have a joint distribution: a joint mass function p(x,y)=P(X=x,Y=y)p(x, y) = P(X = x, Y = y) or a joint density f(x,y)f(x, y); the marginals are recovered by summing or integrating out the other variable. XX and YY are independent if P(X∈A,Y∈B)=P(X∈A) P(Y∈B)P(X \in A, Y \in B) = P(X \in A)\,P(Y \in B) for all intervals (equivalently, all Borel sets) A,BA, B; for discrete variables this means p(x,y)=pX(x) pY(y)p(x, y) = p_X(x)\,p_Y(y), and for densities f(x,y)=fX(x)fY(y)f(x, y) = f_X(x) f_Y(y). A family X1,X2,…X_1, X_2, \dots 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

Cov⁡(X,Y)=E[(X−EX)(Y−EY)]=E[XY]−E[X] E[Y],\operatorname{Cov}(X, Y) = E\big[(X - E X)(Y - E Y)\big] = E[XY] - E[X]\,E[Y],

the correlation is ρ(X,Y)=Cov⁡(X,Y)/(σXσY)\rho(X, Y) = \operatorname{Cov}(X, Y)/(\sigma_X \sigma_Y), and X,YX, Y are uncorrelated if Cov⁡(X,Y)=0\operatorname{Cov}(X, Y) = 0.

Note

∣ρ(X,Y)∣≤1|\rho(X, Y)| \le 1. Indeed, with X′=X−EXX' = X - EX and Y′=Y−EYY' = Y - EY, the quadratic t↦E[(tX′+Y′)2]=t2Var⁡X+2tCov⁡(X,Y)+Var⁡Yt \mapsto E[(tX' + Y')^2] = t^2 \operatorname{Var} X + 2t \operatorname{Cov}(X, Y) + \operatorname{Var} Y is never negative, so its discriminant is ≤0\le 0: Cov⁡(X,Y)2≤Var⁡XVar⁡Y\operatorname{Cov}(X, Y)^2 \le \operatorname{Var} X \operatorname{Var} Y. This is the Cauchy–Schwarz inequality, and the viewpoints section explains why it appears here.

Worked examplesH

A gallery of distributions

Seven distributions do most of the work in applications. Write q=1−pq = 1 - p.

DistributionMass function or densityMeanVarianceModels
Bernoulli(p)(p)P(X=1)=pP(X = 1) = p, P(X=0)=qP(X = 0) = qpppqpqone yes/no trial
Binomial(n,p)(n, p)(nk)pkqn−k\binom nk p^k q^{n-k}, 0≤k≤n0 \le k \le nnpnpnpqnpqsuccesses in nn independent trials
Geometric(p)(p)qk−1pq^{k-1}p, k=1,2,…k = 1, 2, \dots1/p1/pq/p2q/p^2trials up to the first success
Poisson(λ)(\lambda)e−λλk/k!e^{-\lambda}\lambda^k/k!, k=0,1,…k = 0, 1, \dotsλ\lambdaλ\lambdacounts of rare events
Uniform(a,b)(a, b)1b−a\frac{1}{b - a} on [a,b][a, b]a+b2\frac{a + b}{2}(b−a)212\frac{(b - a)^2}{12}a point chosen "at random"
Exponential(λ)(\lambda)λe−λx\lambda e^{-\lambda x}, x≥0x \ge 01/λ1/\lambda1/λ21/\lambda^2waiting times without memory
Normal N(μ,σ2)N(\mu, \sigma^2)1σ2πe−(x−μ)2/(2σ2)\frac{1}{\sigma\sqrt{2\pi}}e^{-(x - \mu)^2/(2\sigma^2)}μ\muσ2\sigma^2sums 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 ∣q∣<1|q| < 1, ∑k≥0qk=11−q\sum_{k \ge 0} q^k = \frac{1}{1 - q}, and a power series may be differentiated term by term inside its radius of convergence: ∑k≥1kqk−1=1(1−q)2\sum_{k \ge 1} k q^{k-1} = \frac{1}{(1-q)^2} and ∑k≥2k(k−1)qk−2=2(1−q)3\sum_{k \ge 2} k(k-1) q^{k-2} = \frac{2}{(1-q)^3}. Hence, for 0<p≤10 < p \le 1,

E[X]=∑k≥1k qk−1p=pp2=1p,E[X(X−1)]=pq∑k≥2k(k−1)qk−2=2qp2,E[X] = \sum_{k \ge 1} k\, q^{k-1} p = \frac{p}{p^2} = \frac1p, \qquad E[X(X-1)] = pq \sum_{k \ge 2} k(k-1) q^{k-2} = \frac{2q}{p^2},

so Var⁡X=E[X(X−1)]+E[X]−(EX)2=2q+p−1p2=qp2\operatorname{Var} X = E[X(X-1)] + E[X] - (E X)^2 = \frac{2q + p - 1}{p^2} = \frac{q}{p^2}. Rolling a fair die until the first six takes 66 rolls on average.

Example— Poisson: shift the index

E[X]=∑k≥1ke−λλkk!=λe−λ∑k≥1λk−1(k−1)!=λe−λeλ=λE[X] = \sum_{k \ge 1} k e^{-\lambda}\frac{\lambda^k}{k!} = \lambda e^{-\lambda} \sum_{k \ge 1} \frac{\lambda^{k-1}}{(k-1)!} = \lambda e^{-\lambda} e^{\lambda} = \lambda, and in the same way E[X(X−1)]=λ2E[X(X-1)] = \lambda^2, so Var⁡X=λ2+λ−λ2=λ\operatorname{Var} X = \lambda^2 + \lambda - \lambda^2 = \lambda. Mean equals variance — a quick test of whether count data could be Poisson.

Example— Uniform and exponential: integrate

For UU uniform on [0,1][0, 1]: E[U]=∫01x dx=12E[U] = \int_0^1 x\,dx = \tfrac12, E[U2]=13E[U^2] = \tfrac13, so Var⁡U=13−14=112\operatorname{Var} U = \tfrac13 - \tfrac14 = \tfrac1{12}; the uniform on [a,b][a, b] is a+(b−a)Ua + (b - a)U, giving the table entries. For TT exponential with rate λ\lambda, integration by parts gives E[T]=∫0∞xλe−λx dx=1λE[T] = \int_0^\infty x \lambda e^{-\lambda x}\,dx = \frac1\lambda and E[T2]=2λ2E[T^2] = \frac{2}{\lambda^2}, so Var⁡T=1λ2\operatorname{Var} T = \frac1{\lambda^2}. Its survival function is P(T>t)=e−λtP(T > t) = e^{-\lambda t}, and therefore

P(T>s+t∣T>s)=e−λ(s+t)e−λs=e−λt=P(T>t)(s,t≥0).P(T > s + t \mid T > s) = \frac{e^{-\lambda(s + t)}}{e^{-\lambda s}} = e^{-\lambda t} = P(T > t) \qquad (s, t \ge 0).

This memoryless property says that a component that has survived ss hours is "as good as new". Among distributions on (0,∞)(0, \infty) with a density, only the exponential ones have it (the survival function GG must satisfy G(s+t)=G(s)G(t)G(s + t) = G(s)G(t), and the only monotone solutions are exponentials).

Example— Normal: the Gaussian integral

Let I=∫−∞∞e−x2/2 dxI = \int_{-\infty}^{\infty} e^{-x^2/2}\,dx. In polar coordinates, I2=∬e−(x2+y2)/2 dx dy=∫02π ⁣∫0∞e−r2/2 r dr dθ=2πI^2 = \iint e^{-(x^2 + y^2)/2}\,dx\,dy = \int_0^{2\pi}\!\int_0^\infty e^{-r^2/2}\, r\,dr\,d\theta = 2\pi, so φ(x)=e−x2/2/2π\varphi(x) = e^{-x^2/2}/\sqrt{2\pi} is a density: the standard normal ZZ. By symmetry E[Z]=0E[Z] = 0, and integrating by parts, E[Z2]=12π∫x⋅xe−x2/2 dx=12π∫e−x2/2 dx=1E[Z^2] = \frac{1}{\sqrt{2\pi}}\int x \cdot x e^{-x^2/2}\,dx = \frac{1}{\sqrt{2\pi}}\int e^{-x^2/2}\,dx = 1. Then X=μ+σZX = \mu + \sigma Z has density 1σφ(x−μσ)\frac{1}{\sigma}\varphi\big(\frac{x - \mu}{\sigma}\big), mean μ\mu and variance σ2\sigma^2. We write Φ(x)=P(Z≤x)\Phi(x) = P(Z \le x); it has no elementary formula, and P(∣Z∣≤1)≈0.683P(|Z| \le 1) \approx 0.683, P(∣Z∣≤1.96)≈0.95P(|Z| \le 1.96) \approx 0.95, P(∣Z∣≤3)≈0.997P(|Z| \le 3) \approx 0.997.

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 f(x)=1π(1+x2)f(x) = \frac{1}{\pi(1 + x^2)} is symmetric about 00, yet ∫∣x∣f(x) dx=∞\int |x| f(x)\,dx = \infty, so E[X]E[X] is undefined — not 00. (It is the tangent of a uniform random angle in (−π2,π2)(-\tfrac\pi2, \tfrac\pi2).) In the St Petersburg game you win 2k2^k coins with probability 2−k2^{-k}, k=1,2,…k = 1, 2, \dots; then E[X]=∑k2k2−k=∞E[X] = \sum_k 2^k 2^{-k} = \infty. Both examples will show that the limit theorems really need their hypotheses.

Theorem— Theorem (Poisson limit of the binomial)

Fix λ>0\lambda > 0 and k∈{0,1,2,… }k \in \{0, 1, 2, \dots\}. Then (nk)(λn)k(1−λn)n−k⟶e−λλkk!\displaystyle \binom nk \Big(\frac\lambda n\Big)^k \Big(1 - \frac\lambda n\Big)^{n-k} \longrightarrow e^{-\lambda}\frac{\lambda^k}{k!} as n→∞n \to \infty.

Proof

For n≥kn \ge k and n>λn > \lambda, rewrite the left side as

λkk!⋅n(n−1)⋯(n−k+1)nk⋅(1−λn)n⋅(1−λn)−k.\frac{\lambda^k}{k!} \cdot \frac{n(n-1)\cdots(n - k + 1)}{n^k} \cdot \Big(1 - \frac\lambda n\Big)^{n} \cdot \Big(1 - \frac\lambda n\Big)^{-k}.

The second factor is a product of kk terms n−jn→1\frac{n - j}{n} \to 1; the third tends to e−λe^{-\lambda} (take logarithms: nln⁡(1−λ/n)→−λn \ln(1 - \lambda/n) \to -\lambda by ln⁡(1+h)/h→1\ln(1 + h)/h \to 1); the fourth tends to 11. 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.

ProofH

Linearity of expectation and indicator variables

Theorem— Theorem (linearity of expectation)

If XX and YY have finite expectations and a,b∈Ra, b \in \R, then aX+bYaX + bY has finite expectation and E[aX+bY]=a E[X]+b E[Y]E[aX + bY] = a\,E[X] + b\,E[Y]. No independence is needed.

Proof

We give the proof for discrete X,YX, Y with joint mass function p(x,y)p(x, y); for general random variables it is the linearity of the integral in measure theory. By the law of the unconscious statistician for g(x,y)=ax+byg(x, y) = ax + by, and since ∣ax+by∣≤∣a∣∣x∣+∣b∣∣y∣|ax + by| \le |a||x| + |b||y| makes every sum below absolutely convergent (so it may be rearranged),

E[aX+bY]=∑x,y(ax+by) p(x,y)=a∑xx∑yp(x,y)+b∑yy∑xp(x,y)=a∑xx pX(x)+b∑yy pY(y).E[aX + bY] = \sum_{x, y} (ax + by)\,p(x, y) = a\sum_x x \sum_y p(x, y) + b \sum_y y \sum_x p(x, y) = a\sum_x x\,p_X(x) + b\sum_y y\,p_Y(y).

The inner sums are the marginals, so this is aE[X]+bE[Y]aE[X] + bE[Y].

∎

The indicator of an event AA is the random variable 1A\mathbf 1_A that equals 11 on AA and 00 off it. It is Bernoulli(P(A))(P(A)), so E[1A]=P(A)E[\mathbf 1_A] = P(A). 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 SS counts successes in nn trials, each succeeding with probability pp, then S=1A1+⋯+1AnS = \mathbf 1_{A_1} + \cdots + \mathbf 1_{A_n}, so E[S]=npE[S] = np — no binomial coefficients needed, and the trials need not even be independent. Similarly, in 2121 flips of a fair coin the number of places where heads is immediately followed by heads is a sum of 2020 indicators, each with probability 14\tfrac14, so its expectation is 55, although overlapping pairs such as HHH are far from independent.

Example— Fixed points of a random permutation

Shuffle nn cards labelled 1,…,n1, \dots, n (or return nn hats to their owners at random). Let NN be the number of cards that end up in their own position, and AiA_i the event "card ii is in place". Then P(Ai)=(n−1)!n!=1nP(A_i) = \frac{(n-1)!}{n!} = \frac1n and N=∑i1AiN = \sum_i \mathbf 1_{A_i}, so

E[N]=n⋅1n=1for every n.E[N] = n \cdot \frac1n = 1 \quad \text{for every } n.

The events AiA_i are dependent (if n−1n - 1 cards are in place, so is the last), but linearity does not care. The variance needs the dependence: for i≠ji \ne j, P(Ai∩Aj)=1n(n−1)P(A_i \cap A_j) = \frac{1}{n(n-1)}, so Cov⁡(1Ai,1Aj)=1n(n−1)−1n2=1n2(n−1)\operatorname{Cov}(\mathbf 1_{A_i}, \mathbf 1_{A_j}) = \frac{1}{n(n-1)} - \frac1{n^2} = \frac{1}{n^2(n-1)}, and by the variance-of-a-sum formula below,

Var⁡N=n⋅1n(1−1n)+n(n−1)⋅1n2(n−1)=1(n≥2).\operatorname{Var} N = n \cdot \frac1n\Big(1 - \frac1n\Big) + n(n-1)\cdot\frac{1}{n^2(n-1)} = 1 \qquad (n \ge 2).

The Lean section proves E[N]=1E[N] = 1 in a completely different way, from Burnside's lemma in group theory, and the first experiment below checks all n!n! permutations for n≤7n \le 7.

Example— Collecting stickers

A school in Accra trades stickers: there are 5050 different ones, and each packet contains one, uniformly at random. How many packets until the album is complete? After i−1i - 1 distinct stickers, each new packet brings a new one with probability 50−i+150\frac{50 - i + 1}{50}, so the waiting time TiT_i for the ii-th new sticker is geometric with mean 5050−i+1\frac{50}{50 - i + 1}. By linearity,

E[T]=∑i=1505051−i=50(1+12+⋯+150)=50H50≈225.E[T] = \sum_{i=1}^{50} \frac{50}{51 - i} = 50\Big(1 + \frac12 + \cdots + \frac1{50}\Big) = 50 H_{50} \approx 225.

In general the coupon collector needs nHn≈nln⁡nn H_n \approx n \ln n draws on average.

ProofH

Independence, covariance and the variance of a sum

Theorem— Theorem (product rule for independent variables)

If XX and YY are independent with finite expectations, then XYXY has finite expectation and E[XY]=E[X] E[Y]E[XY] = E[X]\,E[Y]. Consequently independent variables with finite variances are uncorrelated.

Proof

Discrete case: independence gives p(x,y)=pX(x) pY(y)p(x, y) = p_X(x)\,p_Y(y), so ∑x,y∣xy∣ p(x,y)=(∑x∣x∣pX(x))(∑y∣y∣pY(y))<∞\sum_{x,y} |xy|\,p(x, y) = \big(\sum_x |x|p_X(x)\big)\big(\sum_y |y| p_Y(y)\big) < \infty, and the same computation without absolute values gives E[XY]=∑x,yxy pX(x)pY(y)=E[X] E[Y]E[XY] = \sum_{x, y} xy\,p_X(x)p_Y(y) = E[X]\,E[Y]. For densities the argument is identical with f(x,y)=fX(x)fY(y)f(x, y) = f_X(x) f_Y(y) and Fubini's theorem.

∎

Theorem— Theorem (variance of a sum)

If X1,…,XnX_1, \dots, X_n have finite variances, then

Var⁡(∑i=1nXi)=∑i=1nVar⁡Xi+2∑i<jCov⁡(Xi,Xj).\operatorname{Var}\Big(\sum_{i=1}^n X_i\Big) = \sum_{i=1}^n \operatorname{Var} X_i + 2\sum_{i < j} \operatorname{Cov}(X_i, X_j).

In particular, if the XiX_i are pairwise uncorrelated — for instance pairwise independent — then the variance of the sum is the sum of the variances.

Proof

Let Xi′=Xi−EXiX_i' = X_i - E X_i. By linearity, ∑Xi−E[∑Xi]=∑Xi′\sum X_i - E[\sum X_i] = \sum X_i', so the variance of the sum is E[(∑iXi′)2]=∑i,jE[Xi′Xj′]E\big[(\sum_i X_i')^2\big] = \sum_{i, j} E[X_i' X_j']. The diagonal terms i=ji = j are the variances, and each unordered pair i≠ji \ne j contributes 2E[Xi′Xj′]=2Cov⁡(Xi,Xj)2E[X_i'X_j'] = 2\operatorname{Cov}(X_i, X_j).

∎

Two consequences we use constantly. The binomial variance: the indicators of independent trials are independent, each with variance pqpq, so Var⁡S=npq\operatorname{Var} S = npq. The variance of a sample mean: if X1,…,XnX_1, \dots, X_n are pairwise uncorrelated with common variance σ2\sigma^2, then Xˉn=1n∑Xi\bar X_n = \frac1n\sum X_i has Var⁡Xˉn=1n2⋅nσ2=σ2n\operatorname{Var} \bar X_n = \frac{1}{n^2} \cdot n\sigma^2 = \frac{\sigma^2}{n}. Averaging nn measurements divides the standard deviation by n\sqrt n — the 1/n1/\sqrt n law behind every margin of error.

Example— The product rule needs a hypothesis

Let X=Y=1headsX = Y = \mathbf 1_{\text{heads}} for one fair coin. Then E[XY]=E[X2]=12E[XY] = E[X^2] = \tfrac12, but E[X]E[Y]=14E[X]E[Y] = \tfrac14: here Cov⁡(X,Y)=Var⁡X=14≠0\operatorname{Cov}(X, Y) = \operatorname{Var} X = \tfrac14 \ne 0. And note that for independent X,YX, Y, Var⁡(X−Y)=Var⁡X+Var⁡Y\operatorname{Var}(X - Y) = \operatorname{Var} X + \operatorname{Var} Y — the variances still add, because Var⁡(−Y)=Var⁡Y\operatorname{Var}(-Y) = \operatorname{Var} Y.

Example— Uncorrelated but not independent

Let XX be uniform on {−1,0,1}\{-1, 0, 1\} and Y=X2Y = X^2. Then E[X]=0E[X] = 0 and E[XY]=E[X3]=0E[XY] = E[X^3] = 0, so Cov⁡(X,Y)=0\operatorname{Cov}(X, Y) = 0. But YY is a function of XX: P(X=1,Y=0)=0P(X = 1, Y = 0) = 0, whereas P(X=1) P(Y=0)=13⋅13P(X = 1)\,P(Y = 0) = \tfrac13 \cdot \tfrac13. Covariance measures only linear dependence. (This example is checked in Lean below.)

ProofH

Inequalities and the law of large numbers

Theorem— Theorem (Markov's inequality)

If X≥0X \ge 0 has finite expectation and a>0a > 0, then P(X≥a)≤E[X]aP(X \ge a) \le \dfrac{E[X]}{a}.

Proof

Pointwise, a 1{X≥a}≤Xa\,\mathbf 1_{\{X \ge a\}} \le X: where X≥aX \ge a the left side is a≤Xa \le X, and elsewhere it is 0≤X0 \le X. Expectation is monotone (a consequence of linearity and E[W]≥0E[W] \ge 0 for W≥0W \ge 0), so a P(X≥a)≤E[X]a\,P(X \ge a) \le E[X].

∎

Theorem— Theorem (Chebyshev's inequality)

If XX has mean μ\mu and finite variance σ2\sigma^2, then for every c>0c > 0,   P(∣X−μ∣≥c)≤σ2c2\;P(|X - \mu| \ge c) \le \dfrac{\sigma^2}{c^2}. Equivalently, P(∣X−μ∣≥kσ)≤1k2P(|X - \mu| \ge k\sigma) \le \dfrac1{k^2} for k>0k > 0 (when σ>0\sigma > 0).

Proof

The events {∣X−μ∣≥c}\{|X - \mu| \ge c\} and {(X−μ)2≥c2}\{(X - \mu)^2 \ge c^2\} are the same. Apply Markov's inequality to the non-negative variable (X−μ)2(X - \mu)^2, whose expectation is σ2\sigma^2, with a=c2a = c^2.

∎

Chebyshev's inequality cannot be improved using the variance alone: for k≥1k \ge 1, the variable taking the values ±k\pm k with probability 12k2\frac{1}{2k^2} each and 00 otherwise has mean 00, variance 11 and P(∣X∣≥k)=1k2P(|X| \ge k) = \frac1{k^2} exactly.

Theorem— Theorem (weak law of large numbers)

Let X1,X2,…X_1, X_2, \dots be pairwise uncorrelated (for instance, independent) random variables with common mean μ\mu and common finite variance σ2\sigma^2, and let Xˉn=1n(X1+⋯+Xn)\bar X_n = \frac1n(X_1 + \cdots + X_n). Then for every ε>0\varepsilon > 0,

P(∣Xˉn−μ∣≥ε)≤σ2nε2→n→∞0.P\big(|\bar X_n - \mu| \ge \varepsilon\big) \le \frac{\sigma^2}{n\varepsilon^2} \xrightarrow[n \to \infty]{} 0 .

That is, Xˉn\bar X_n converges in probability to μ\mu.

Proof

By linearity, E[Xˉn]=1n⋅nμ=μE[\bar X_n] = \frac1n \cdot n\mu = \mu. By the variance-of-a-sum theorem and Var⁡(cW)=c2Var⁡W\operatorname{Var}(cW) = c^2\operatorname{Var}W, Var⁡Xˉn=σ2n\operatorname{Var} \bar X_n = \frac{\sigma^2}{n}. Chebyshev's inequality applied to Xˉn\bar X_n with c=εc = \varepsilon gives the bound, which tends to 00 as n→∞n \to \infty for fixed ε\varepsilon.

∎

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.

00.250.50.75105001,0001,5002,000number of flipsproportion of heads
  • 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 Sn−n/2S_n - n/2 typically grows like n\sqrt n; only the proportion settles.

How sharp is the bound? For 10 00010\,000 fair coin flips and ε=0.02\varepsilon = 0.02, Chebyshev gives P(∣Xˉn−12∣≥0.02)≤1/410 000⋅0.0004=0.0625P(|\bar X_n - \tfrac12| \ge 0.02) \le \frac{1/4}{10\,000 \cdot 0.0004} = 0.0625, while the true value is about 6×10−56 \times 10^{-5}. 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 2e−2nε22e^{-2n\varepsilon^2}. 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.) XiX_i, finite mean alone suffices.
  • The strong law of large numbers (Kolmogorov, 1933; Etemadi's 1981 proof needs only pairwise independence): if the XiX_i are pairwise independent, identically distributed, with E∣X1∣<∞E|X_1| < \infty, then P(Xˉn→μ)=1P(\bar X_n \to \mu) = 1. The strong law says almost every individual sequence of averages converges; the weak law only says that, at each large nn, a deviation is unlikely. It is proved in Mathlib (see below).

The hypothesis E∣X1∣<∞E|X_1| < \infty matters: for i.i.d. Cauchy variables, Xˉn\bar X_n has exactly the same Cauchy distribution as X1X_1 for every nn — averaging does not help at all. The law of large numbers is also the principle behind Monte Carlo integration: to estimate ∫01g\int_0^1 g, average g(U1),…,g(Un)g(U_1), \dots, g(U_n) for independent uniform UiU_i; the error is of order σ/n\sigma/\sqrt n, whatever the dimension.

ProofH

The central limit theorem

The law of large numbers says Xˉn−μ→0\bar X_n - \mu \to 0. The fluctuations have size σ/n\sigma/\sqrt n, so we magnify them by n/σ\sqrt n/\sigma and ask about the shape of what we see.

Definition— convergence in distribution

Random variables WnW_n converge in distribution to WW if P(Wn≤x)→P(W≤x)P(W_n \le x) \to P(W \le x) at every xx where x↦P(W≤x)x \mapsto P(W \le x) is continuous. When the limit is normal (which has a continuous distribution function), this means convergence at every xx.

Theorem— Theorem (central limit theorem, Lindeberg–Lévy)

Let X1,X2,…X_1, X_2, \dots be independent and identically distributed with mean μ\mu and finite variance σ2>0\sigma^2 > 0, and let Sn=X1+⋯+XnS_n = X_1 + \cdots + X_n. Then for every x∈Rx \in \R,

P(Sn−nμσn≤x)⟶Φ(x)=∫−∞xe−t2/22π dt(n→∞).P\left(\frac{S_n - n\mu}{\sigma\sqrt n} \le x\right) \longrightarrow \Phi(x) = \int_{-\infty}^x \frac{e^{-t^2/2}}{\sqrt{2\pi}}\,dt \qquad (n \to \infty).

Proof

A proof sketch under an extra hypothesis. Assume the moment generating function M(t)=E[etX1]M(t) = E[e^{tX_1}] is finite for ∣t∣<t0|t| < t_0 (this is stronger than finite variance). Put Yi=(Xi−μ)/σY_i = (X_i - \mu)/\sigma, so E[Yi]=0E[Y_i] = 0, E[Yi2]=1E[Y_i^2] = 1, and MY(t)=E[etY1]=1+t22+o(t2)M_Y(t) = E[e^{tY_1}] = 1 + \frac{t^2}{2} + o(t^2) as t→0t \to 0 (Taylor's theorem; the moment generating function can be differentiated under the expectation inside its interval of convergence). The standardised sum is Zn=1n∑iYiZ_n = \frac{1}{\sqrt n}\sum_i Y_i, and by independence the expectation of a product of the independent factors etYi/ne^{tY_i/\sqrt n} is the product of expectations:

E[etZn]=MY(tn)n=(1+t22n+o(1n))n⟶et2/2,E\big[e^{tZ_n}\big] = M_Y\Big(\frac{t}{\sqrt n}\Big)^n = \Big(1 + \frac{t^2}{2n} + o\Big(\frac1n\Big)\Big)^n \longrightarrow e^{t^2/2},

which is the moment generating function of N(0,1)N(0, 1) (complete the square in ∫etxφ(x) dx\int e^{tx}\varphi(x)\,dx). A continuity theorem (Curtiss, 1942) says that convergence of moment generating functions on a neighbourhood of 00 implies convergence in distribution; we cite it without proof. The general theorem replaces etXe^{tX} by the characteristic function E[eitX]E[e^{itX}], 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

100100 fair coin flips: SS has mean 5050 and standard deviation 55. Since SS takes whole-number values, P(S≥60)=P(S≥59.5)P(S \ge 60) = P(S \ge 59.5), and the continuity correction approximates this by P(Z≥59.5−505)=P(Z≥1.9)≈0.0287P(Z \ge \frac{59.5 - 50}{5}) = P(Z \ge 1.9) \approx 0.0287; the exact value is 0.02840.0284 (without the correction one gets 0.02280.0228). For the sum of 3030 dice (mean 105105, variance 30⋅3512=87.530 \cdot \frac{35}{12} = 87.5), P(S≥120)≈P(Z≥119.5−10587.5)≈0.0606P(S \ge 120) \approx P\big(Z \ge \frac{119.5 - 105}{\sqrt{87.5}}\big) \approx 0.0606, against an exact 0.06070.0607. And the germination promise in the motivation: 10 00010\,000 seeds with p=0.9p = 0.9 give mean 90009000 and standard deviation 900=30\sqrt{900} = 30, so about 95%95\% of the time the count lies within 1.96×30≈591.96 \times 30 \approx 59 of 90009000.

How fast? The Berry–Esseen theorem (1941–42) quantifies the convergence: if ρ=E∣X1−μ∣3<∞\rho = E|X_1 - \mu|^3 < \infty, then

sup⁡x∈R∣P(Sn−nμσn≤x)−Φ(x)∣≤Cρσ3n,\sup_{x \in \R}\left| P\Big(\frac{S_n - n\mu}{\sigma\sqrt n} \le x\Big) - \Phi(x)\right| \le \frac{C\rho}{\sigma^3\sqrt n},

where CC is a universal constant (known to satisfy C≤0.4748C \le 0.4748, Shevtsova 2011). Skewed distributions, with large ρ/σ3\rho/\sigma^3, need larger nn; the third experiment measures this for a die and for a coin with P(heads)=0.1P(\text{heads}) = 0.1.

What the theorem does not say.

  1. It does not say that data become normal. A sample of 10 00010\,000 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.
  2. It needs finite variance. Averages of i.i.d. Cauchy variables are Cauchy for every nn, and heavy-tailed sums converge (when they converge at all) to other "stable" laws, with a different scaling than n\sqrt n.
  3. 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.
  4. It controls absolute, not relative, error. Far in the tails, where Φ\Phi 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.

Formal mathematicsF

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):

expectation_sum_indicatorsLean 4Proved here from basic factsFormally verified
/-- **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)
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityTheory.leanTry it in the Lean web editor
perm_fixed_points_averageLean 4Proved here from basic factsFormally verified
/-- **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]
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityTheory.leanTry it in the Lean web editor

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:

binomial_meanLean 4Applies a library theoremFormally verified
/-- **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
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityTheory.leanTry it in the Lean web editor
geometric_meanLean 4Proved here from basic factsFormally verified
/-- **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
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityTheory.leanTry it in the Lean web editor
exponential_memorylessLean 4Proved here from basic factsFormally verified
/-- **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
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityTheory.leanTry it in the Lean web editor
gaussian_meanLean 4Applies a library theoremFormally verified
/-- 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
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityTheory.leanTry it in the Lean web editor
gaussian_varianceLean 4Applies a library theoremFormally verified
/-- 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
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityTheory.leanTry it in the Lean web editor
poisson_limitLean 4Applies a library theoremFormally verified
/-- **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 hp
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityTheory.leanTry it in the Lean web editor

Independence. 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):

expectation_mul_indepLean 4Applies a library theoremFormally verified
/-- **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
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityTheory.leanTry it in the Lean web editor
variance_add_indepLean 4Applies a library theoremFormally verified
/-- **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
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityTheory.leanTry it in the Lean web editor
avg3Lean 4Formally verified
/-- 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
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityTheory.leanTry it in the Lean web editor
uncorrelated_not_independentLean 4Proved here from basic factsFormally verified
/-- **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_num
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityTheory.leanTry it in the Lean web editor

Markov, 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):

markovLean 4Applies a library theoremFormally verified
/-- **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
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityTheory.leanTry it in the Lean web editor
chebyshevLean 4Proved here from basic factsFormally verified
/-- **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)
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityTheory.leanTry it in the Lean web editor
chebyshev_libraryLean 4Applies a library theoremFormally verified
/-- 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 hc
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityTheory.leanTry it in the Lean web editor

The weak law of large numbers with its explicit rate σ2/(nε2)\sigma^2/(n\varepsilon^2), 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:

weak_law_boundLean 4Proved here from basic factsFormally verified
/-- **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
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityTheory.leanTry it in the Lean web editor
weak_lawLean 4Proved here from basic factsFormally verified
/-- **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 ring
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityTheory.leanTry it in the Lean web editor

The 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:

strong_lawLean 4Applies a library theoremFormally verified
/-- **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
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityTheory.leanTry it in the Lean web editor
cltLean 4Applies a library theoremFormally verified
/-- **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 hident
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityTheory.leanTry it in the Lean web editor

What 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.

ComputationC

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 1/e1/e) and the whole distribution, which is close to Poisson(1)(1).

Fixed points of random permutations, all n! of themPythonExhaustive finite checkExact computationComputationally tested
"""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()
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

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.

Chebyshev, Hoeffding and the normal curve against exact coin tailsPythonExact computationNumerical approximationComputationally tested
"""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()
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

Finally, how fast does the central limit theorem take hold? The exact distribution of a sum of nn dice or of nn lopsided coins is computed by repeated convolution, and its largest gap from the normal distribution function is compared with the Berry–Esseen bound.

The central limit theorem at work: exact sums of dice and coinsPythonNumerical approximationComputationally tested
"""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()
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

The first experiment is exhaustive for finitely many nn 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 nn — that is the job of the proofs above and of the Lean module.

Explore

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.

0%10%20%23456789101112sum of the two dice5310917719627932529021217212760
  • 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 nn steps of ±1\pm1. The position SnS_n has mean 00 and variance nn (variances of independent steps add), so its typical size is n\sqrt n, not nn: after 100100 steps, about 1010 from the start. Increase nn and check the n\sqrt n curve. Dividing by nn gives the law of large numbers; dividing by n\sqrt n gives the central limit theorem.
Exercises

Exercises

1. Probability theory

Warm-upHuman

You 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

CoreHuman

A fair coin is flipped 4141 times. A double is a position ii (1≤i≤401 \le i \le 40) where flips ii and i+1i + 1 are both heads; overlapping doubles count separately (HHH contains two). What is the expected number of doubles?

3. Probability theory

CoreHuman

In which of these situations is E[XY]=E[X] E[Y]E[XY] = E[X]\,E[Y] guaranteed? (All variables have finite variance. Choose all that apply.)

Choose all that apply

4. Probability theory

CoreHuman

Let SS be the number of heads in 400400 flips of a fair coin. What is the smallest cc for which Chebyshev's inequality guarantees P(∣S−200∣≥c)≤14P(|S - 200| \ge c) \le \tfrac14?

5. Probability theory

CoreHuman

The proof of the weak law of large numbers has four steps: (1) E[Xˉn]=μE[\bar X_n] = \mu; (2) Var⁡Xˉn=σ2/n\operatorname{Var} \bar X_n = \sigma^2/n; (3) apply Chebyshev's inequality to Xˉn\bar X_n; (4) let n→∞n \to \infty. Which step uses the hypothesis that the XiX_i are pairwise uncorrelated?

Choose one

6. Probability theory

CoreHuman

Which statement is a correct consequence of the central limit theorem?

Choose one

7. Probability theory

StretchHuman

Ten letters are put into ten addressed envelopes uniformly at random. Let NN be the number of letters in the right envelope. What is Var⁡N\operatorname{Var} N?

Choose one

8. Probability theory

CoreFormal

Which Lean statement correctly formalises Chebyshev's inequality c2 P(∣X−EX∣≥c)≤Var⁡Xc^2\,P(|X - E X| \ge c) \le \operatorname{Var} X? (Here μ is a probability measure, μ[X] is EXE X and Var[X; μ] is Var⁡X\operatorname{Var} X.)

Choose one

9. Probability theory

StretchComputational

Write tail(n, k) returning the exact probability, as a Fraction, that the number of heads SS in nn fair coin flips satisfies ∣S−n/2∣≥k|S - n/2| \ge k. Then write chebyshev(n, k) returning Chebyshev's bound n/4k2\frac{n/4}{k^2} as a Fraction. The tests check that the bound always holds and is far from sharp for large nn.

Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.
Common misconceptionsH

Common misconceptions

Misconception

"E[XY]=E[X]E[Y]E[XY] = E[X]E[Y] always." This holds exactly when XX and YY are uncorrelated; independence is the usual sufficient condition. For X=Y=1headsX = Y = \mathbf 1_{\text{heads}}, E[XY]=12E[XY] = \tfrac12 but E[X]E[Y]=14E[X]E[Y] = \tfrac14. Contrast linearity, E[X+Y]=E[X]+E[Y]E[X + Y] = E[X] + E[Y], 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 XX uniform on {−1,0,1}\{-1, 0, 1\} and Y=X2Y = X^2, YY is completely determined by XX, yet Cov⁡(X,Y)=0\operatorname{Cov}(X, Y) = 0. (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 12\tfrac12 because later flips swamp the early ones, while the excess number of heads typically grows like n\sqrt n.

Misconception

"Every distribution has a mean; a symmetric one has mean at its centre." The Cauchy distribution is symmetric about 00 but has no expectation, and the average of nn 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 Var⁡(X−Y)=Var⁡X−Var⁡Y\operatorname{Var}(X - Y) = \operatorname{Var} X - \operatorname{Var} Y." For independent (or uncorrelated) XX and YY, Var⁡(X−Y)=Var⁡X+Var⁡Y\operatorname{Var}(X - Y) = \operatorname{Var} X + \operatorname{Var} Y: subtracting an independent noisy quantity adds noise. And without that hypothesis, the covariance term ±2Cov⁡(X,Y)\pm 2\operatorname{Cov}(X, Y) appears.

ViewpointsH

Many ways of seeing

Geometry— Random variables as vectors: covariance is an inner product

Random variables with finite variance form a vector space L2L^2, and ⟨X,Y⟩=E[XY]\langle X, Y \rangle = E[XY] is an inner product on it (after identifying variables that agree with probability 11). On centred variables the geometry is statistical: Var⁡X=∥X−EX∥2\operatorname{Var} X = \|X - EX\|^2 is a squared length, Cov⁡(X,Y)\operatorname{Cov}(X, Y) is an inner product, the correlation ρ\rho is the cosine of the angle between X−EXX - EX and Y−EYY - EY, and ∣ρ∣≤1|\rho| \le 1 is the Cauchy–Schwarz inequality. "Uncorrelated" means orthogonal, and Var⁡(X+Y)=Var⁡X+Var⁡Y\operatorname{Var}(X + Y) = \operatorname{Var} X + \operatorname{Var} Y for uncorrelated variables is Pythagoras' theorem. The expectation E[X]E[X] itself is the orthogonal projection of XX onto the line of constants — the constant cc minimising E[(X−c)2]E[(X - c)^2] — 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 E[X]E[X] is the Lebesgue integral ∫ΩX dP\int_\Omega X\,dP, 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 φX(t)=E[eitX]\varphi_X(t) = E[e^{itX}] is the Fourier transform of the distribution, which turns convolution into multiplication: φX+Y=φXφY\varphi_{X+Y} = \varphi_X\varphi_Y. The central limit theorem then says that φY(t/n)n→e−t2/2\varphi_Y(t/\sqrt n)^n \to e^{-t^2/2} — and e−x2/2e^{-x^2/2} 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 2\sqrt 2", 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 {0,1,2,… }\{0, 1, 2, \dots\}, the probability generating function GX(s)=E[sX]=∑kP(X=k)skG_X(s) = E[s^X] = \sum_k P(X = k)s^k packages the distribution as a power series; independence turns sums into products, GX+Y=GXGYG_{X+Y} = G_X G_Y, so the binomial is (q+ps)n(q + ps)^n and moments come from derivatives at s=1s = 1 (E[X]=G′(1)E[X] = G'(1)). The average number of fixed points has a group-theoretic meaning too: for any finite group GG acting on a finite set, Burnside's lemma says that the average number of points fixed by a random element of GG equals the number of orbits. The symmetric group acting on {1,…,n}\{1, \dots, n\} 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 t\sqrt t law of diffusion, the continuous version of the random walk's n\sqrt n. 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 ∂tu=D ∂x2u\partial_t u = D\,\partial_x^2 u, whose fundamental solution is a Gaussian. In statistical mechanics, the law of large numbers is why macroscopic quantities such as pressure, an average over ∼1023\sim 10^{23} 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 Ω\Omega, "and", "or" and "not" are intersection, union and complement, and a random variable is a function X:Ω→RX : \Omega \to \R with X−1((−∞,x])∈FX^{-1}((-\infty, x]) \in \mathcal F — a measurable function. Its distribution is the pushforward measure P∘X−1P \circ X^{-1} on R\R. The insistence on a σ-algebra F\mathcal F 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 [0,1)[0, 1). 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 x↦κ(x,⋅)x \mapsto \kappa(x, \cdot)) as morphisms form a category: kernels compose by "first sample from κ\kappa, then from λ\lambda", exactly as stochastic matrices multiply. Giry (1982) showed that the assignment X↦P(X)X \mapsto \mathcal P(X), the space of probability measures on XX, is a monad whose Kleisli category is this category of kernels; the functor P\mathcal P sends a measurable map to pushforward, so the distribution of a random variable X:Ω→RX : \Omega \to \R is P(X)\mathcal P(X) applied to PP. 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 & global context

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 p=12p = \tfrac12, 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

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.