Two and a half million wrong answers
In 1936 the American magazine The Literary Digest mailed questionnaires to about ten million people, asking how they would vote in the presidential election. About million replied — one of the largest polls ever taken — and the magazine predicted a comfortable win for Alf Landon. Franklin Roosevelt won in a landslide, with about of the vote. The young pollster George Gallup, using a far smaller sample chosen to represent the voting public, correctly predicted Roosevelt's victory.
How can a few thousand answers beat two million? Because how a sample is chosen matters far more than how big it is. The Digest's names came largely from telephone directories and lists of car owners — in 1936, mostly better-off households — and the people who bothered to reply were not typical either.
Today, statistical sampling measures unemployment, crop yields and public health in almost every country. India's National Sample Survey, set up in 1950 under the statistician Prasanta Chandra Mahalanobis, was one of the first to do this on a national scale. This lesson explains why careful sampling works, how to say how far to trust its answers, and how to think clearly about relationships between variables — including when a relationship is, and is not, evidence of a cause.
One spoonful of soup
Analogy, not a formal construction
To check the salt in a big pot of soup, you do not drink the whole pot: you stir it well and taste one spoonful. Stirring makes every spoonful like every other, so one tells you about all of them — and a spoonful is enough for a large pot as well as a small one. But if you never stir, a spoonful from the top tells you nothing reliable, however large your spoon. Random sampling is the statistician's way of stirring. (This is an analogy: the mathematics behind it is the behaviour of random samples described below.)
There are two very different kinds of error in a sample estimate.
- Chance error (sampling variability): different random samples give different answers, scattered around the truth. Chance errors are as likely to be too high as too low, and they shrink as the sample grows.
- Bias (systematic error): the method of collecting data pushes every answer in the same direction — towards households with telephones, towards people with strong opinions. Bias does not shrink with sample size. A bigger biased sample only gives a more precise wrong answer.
Definitions
Definition— population, sample, parameter, statistic
The population is the whole group we want to know about; a sample is the part of it that we actually observe. A parameter is a number describing the population (the proportion of all households with a rainwater tank); a statistic is a number computed from the sample (the proportion of sampled households with one), used to estimate the parameter.
Definition— simple random sample
In a simple random sample of size , every subset of members of the population is equally likely to be the sample.
Definition— bias
A method of sampling or measuring is biased if it tends to give estimates that are systematically too high or too low. Common sources: selection bias (some members are less likely to be included — people without telephones), non-response (those chosen do not all answer, and those who answer differ from those who do not), voluntary response (people choose themselves, and strong opinions are over-represented), and response bias (leading questions, or answers people are embarrassed to give).
Definition— sampling distribution and standard error
The sampling distribution of a statistic is the pattern of values it takes over all possible random samples. Its standard deviation is the statistic's standard error (SE). For the proportion in a simple random sample of size , taken from a population much larger than ,
Definition— margin of error and confidence interval
A confidence interval for a proportion is ; the half-width is the margin of error. "" describes the method: in the long run, about of intervals built this way from random samples contain the true .
Definition— normal distribution
The normal distribution with mean and standard deviation is the bell-shaped curve . About of its area lies within of , about within , and about within . It is a model: many sampling distributions are close to normal, which is where the number comes from.
For paired data , write for the means and
Definition— least-squares line and correlation coefficient
The residual of the point from the line is . The least-squares line is the line that makes the sum of squared residuals as small as possible. The correlation coefficient is
(defined when and ). It measures the strength and direction of a linear association.
Worked examples
Example— Spotting bias
- A radio station asks listeners to text in whether they support a new stadium: voluntary response — people with strong feelings reply.
- A survey about public transport is carried out at a car park: selection bias — people who take the bus are left out.
- "Do you agree that the dangerous old bridge should be replaced?" — a leading question (response bias).
- A health survey reaches only the people who are at home in the afternoon: selection and non-response bias — workers and students are missed.
Example— A margin of error
A water agency surveys a simple random sample of households in a town of ; of them, , collect rainwater in a tank. The standard error is about , so the margin of error is , and the confidence interval runs from about to . The agency can report "about , give or take percentage points". (The sample is only of the town, so the approximation "population much larger than " is reasonable.)
Example— Fitting a line
Five students record the hours they spent revising and their quiz score out of :
| (hours) | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| (score) | 2 | 4 | 5 | 4 | 5 |
Here , ; the deviations are and , so , and . As we prove below, the least-squares line has slope and intercept :
The residuals add up to , and their squares add up to . With five students, of course, this describes these five and nothing more.
Example— A non-example: r = 0, yet a perfect relationship
For the points with , , so . Yet is completely determined by . The correlation coefficient detects only linear association; means "no linear association", not "no relationship". Always plot the data.
What can be proved, and how
Statistics rests on two kinds of argument: probability, which describes how random samples behave, and algebra, which describes the summaries we compute. Both can be proved. Whether a particular sample was really random, or a particular cause is real, is a question about the world, which no theorem can settle.
Theorem— Theorem 1 (the mean is the least-squares centre)
For numbers with mean and any number ,
In particular is smallest exactly when .
Proof
First, the deviations from the mean add up to zero: . Now write and expand the square:
The middle term is . The last term is never negative, and it is only when .
∎
Theorem— Theorem 2 (the 1/√n law)
Suppose are independent measurements, each with mean and standard deviation (for example, values drawn at random, with replacement, from a population). Then their average has mean and standard deviation .
Proof
This uses two facts proved in probability theory: the variance (the square of the standard deviation) of a sum of independent random quantities is the sum of their variances, and multiplying a random quantity by a constant multiplies its variance by (and its mean by ). So , and
The mean of is , because means always add, independent or not.
∎
A proportion is an average of s and s (one for each "yes"), with ; this gives the standard error above. (Sampling without replacement makes the measurements slightly dependent and the spread slightly smaller; the difference is negligible when the sample is a small part of the population.) The law has a striking consequence: to halve the margin of error you need four times as many observations. And notice what is missing from the formula: the size of the population. A random sample of is about as informative about a country of million as about a city of — the spoonful of soup.
Where does come from? The central limit theorem, which you will meet in probability theory, says that for large the sampling distribution of is approximately normal — whatever the shape of the population. So about of samples give a within standard errors of ; and is within standard errors of in exactly those samples. We state this theorem here without proof (Mathlib has a formal proof, shown in the formal section).
Theorem— Theorem 3 (the least-squares line)
Suppose the are not all equal, so . For every line , the sum of squared residuals is
Hence the least-squares line is with
it passes through the point of means , and its sum of squared residuals is .
Proof
Centre the data: let and , so that . Writing , each residual is
Squaring and adding, the cross term is , so
Completing the square in , , which is the formula. Since and , both squared terms are at least , and both are exactly when and . Then : the line passes through .
∎
Theorem— Theorem 4 (correlation lies between −1 and 1)
If and , then . Moreover, is the least sum of squared residuals, so exactly when all the points lie on one straight line.
Proof
The least sum of squared residuals is (Theorem 3), and
A sum of squares cannot be negative, so , that is . And exactly when this sum is , that is, when every residual is and every point lies on the least-squares line. (Conversely, if all points lie on a line , that line has , so the least possible value is .)
∎
The inequality hidden in this proof is the Cauchy–Schwarz inequality , applied to and . The number is often described as "the fraction of the variation in explained by the line": the line reduces the sum of squares from (using alone, Theorem 1) to . In the revision example, and the sum of squares falls from to .
Correlation and causation
Across many towns, ice-cream sales and the number of people rescued from the sea rise and fall together. Ice cream does not cause drowning: hot weather drives both. A third variable that influences both of the variables we are looking at is a confounder. Other ways for a correlation to arise without causing :
- Reverse causation: towns with more police officers may have more crime — perhaps because more officers are sent where there is crime.
- Chance: search enough pairs of variables and some will be strongly correlated by coincidence.
- Selection: if only some cases are observed (only successful companies, only patients who reached hospital), relationships can appear that do not exist in the whole population.
The strongest evidence for causation comes from a randomised experiment: assign the treatment by chance — by lottery, not by choice — to some subjects and not to others. Randomisation balances confounders, including those nobody thought of, between the groups, so a clear difference in outcomes is evidence that the treatment caused it. Ronald Fisher made randomisation the foundation of experimental design in the 1920s and 1930s, and randomised controlled trials are now the standard test of new medicines.
When experiments are impossible or unethical, careful observational studies can still build a strong case. The link between smoking and lung cancer, established by Richard Doll, Austin Bradford Hill and others from 1950 onwards, rested on many studies: a strong association, a dose–response relationship (more cigarettes, more risk), the right order in time, consistency across countries, and a plausible biological mechanism.
The algebra of statistics, checked by Lean
Lean cannot check that a sample was random or that a cause is real. It can check the algebra on which the methods rest. Data are lists , that is .
/-- The **mean** `x̄ = (x₁ + ⋯ + xₙ)/n` of `n` data values `x : Fin n → ℝ`. -/
noncomputable def mean {n : ℕ} (x : Fin n → ℝ) : ℝ := (∑ i, x i) / nTheorem 1, in three steps:
/-- The deviations from the mean add up to zero: `Σ (xᵢ − x̄) = 0`. -/
theorem sum_sub_mean {n : ℕ} (hn : 0 < n) (x : Fin n → ℝ) : ∑ i, (x i - mean x) = 0 := by
have hn' : (n : ℝ) ≠ 0 := by exact_mod_cast hn.ne'
rw [sum_sub_distrib, sum_const, card_univ, Fintype.card_fin, nsmul_eq_mul, mean]
field_simp
ring/-- **Spread about any point `c`:** `Σ (xᵢ − c)² = Σ (xᵢ − x̄)² + n (x̄ − c)²`. Write
`xᵢ − c = (xᵢ − x̄) + (x̄ − c)` and expand; the cross term is `2(x̄ − c) Σ (xᵢ − x̄) = 0`. -/
theorem sum_sq_sub {n : ℕ} (hn : 0 < n) (x : Fin n → ℝ) (c : ℝ) :
∑ i, (x i - c) ^ 2 = ∑ i, (x i - mean x) ^ 2 + n * (mean x - c) ^ 2 := by
have h0 := sum_sub_mean hn x
calc ∑ i, (x i - c) ^ 2
= ∑ i, ((x i - mean x) ^ 2 + 2 * (mean x - c) * (x i - mean x) + (mean x - c) ^ 2) :=
sum_congr rfl fun i _ => by ring
_ = ∑ i, (x i - mean x) ^ 2 + 2 * (mean x - c) * ∑ i, (x i - mean x) +
n * (mean x - c) ^ 2 := by
rw [sum_add_distrib, sum_add_distrib, ← mul_sum, sum_const, card_univ, Fintype.card_fin,
nsmul_eq_mul]
_ = ∑ i, (x i - mean x) ^ 2 + n * (mean x - c) ^ 2 := by rw [h0]; ring/-- **The mean minimises the sum of squared deviations:** `Σ (xᵢ − x̄)² ≤ Σ (xᵢ − c)²` for
every number `c`, with the extra amount exactly `n (x̄ − c)²`. -/
theorem mean_minimizes {n : ℕ} (hn : 0 < n) (x : Fin n → ℝ) (c : ℝ) :
∑ i, (x i - mean x) ^ 2 ≤ ∑ i, (x i - c) ^ 2 := by
rw [sum_sq_sub hn x c]
have : 0 ≤ (n : ℝ) * (mean x - c) ^ 2 := by positivity
linarithThe Cauchy–Schwarz inequality, proved by the same least-squares idea (for every , ; choose the best ), and Mathlib's version:
/-- **The Cauchy–Schwarz inequality** `(Σ fᵢgᵢ)² ≤ (Σ fᵢ²)(Σ gᵢ²)`, by least squares.
If `Σ gᵢ² = 0`, every `gᵢ` is `0` and both sides vanish. Otherwise, for every `t`,
`0 ≤ Σ (fᵢ − t gᵢ)² = Σ fᵢ² − 2t Σ fᵢgᵢ + t² Σ gᵢ²`; the best choice `t = Σ fᵢgᵢ / Σ gᵢ²` gives
`0 ≤ Σ fᵢ² − (Σ fᵢgᵢ)² / Σ gᵢ²`. -/
theorem cauchy_schwarz {n : ℕ} (f g : Fin n → ℝ) :
(∑ i, f i * g i) ^ 2 ≤ (∑ i, f i ^ 2) * ∑ i, g i ^ 2 := by
set A := ∑ i, f i ^ 2
set B := ∑ i, f i * g i
set C := ∑ i, g i ^ 2
have hC : 0 ≤ C := sum_nonneg fun i _ => sq_nonneg (g i)
-- the sum of squares `Σ (fᵢ − t gᵢ)²`, expanded
have key : ∀ t : ℝ, 0 ≤ A - 2 * t * B + t ^ 2 * C := by
intro t
have h : ∑ i, (f i - t * g i) ^ 2 = A - 2 * t * B + t ^ 2 * C := by
simp only [A, B, C, mul_sum, ← sum_sub_distrib, ← sum_add_distrib]
exact sum_congr rfl fun i _ => by ring
rw [← h]
exact sum_nonneg fun i _ => sq_nonneg _
rcases hC.eq_or_lt with hC0 | hCpos
· -- every `gᵢ = 0`, so `B = 0`
have hg : ∀ i, g i = 0 := by
intro i
have := (sum_eq_zero_iff_of_nonneg fun j _ => sq_nonneg (g j)).1 hC0.symm i (mem_univ i)
exact pow_eq_zero_iff (two_ne_zero) |>.1 this
have hB : B = 0 := sum_eq_zero fun i _ => by rw [hg i, mul_zero]
rw [hB, ← hC0]
simp
· -- the best `t`
have h := key (B / C)
have h' : 0 ≤ A * C - B ^ 2 := by
have e : A - 2 * (B / C) * B + (B / C) ^ 2 * C = (A * C - B ^ 2) / C := by
field_simp
ring
rw [e] at h
exact (div_nonneg_iff.1 h).elim (fun h => h.1) fun h => absurd h.2 (not_le.2 hCpos)
linarith/-- The same inequality from Mathlib: `Finset.sum_mul_sq_le_sq_mul_sq`. -/
theorem cauchy_schwarz_library {n : ℕ} (f g : Fin n → ℝ) :
(∑ i, f i * g i) ^ 2 ≤ (∑ i, f i ^ 2) * ∑ i, g i ^ 2 :=
sum_mul_sq_le_sq_mul_sq univ f gThe correlation coefficient and Theorem 4. (Lean defines even when or is zero, by its convention , so the bound holds without hypotheses.)
/-- The **sum of products of deviations** `Sxy = Σ (xᵢ − x̄)(yᵢ − ȳ)`. With `y = x` it is
`Sxx = Σ (xᵢ − x̄)²`, which measures the spread of the `x`-values. -/
noncomputable def Sxy {n : ℕ} (x y : Fin n → ℝ) : ℝ := ∑ i, (x i - mean x) * (y i - mean y)/-- The **correlation coefficient** `r = Sxy / √(Sxx · Syy)`. (If all the `x`-values or all the
`y`-values are equal, `r` is undefined; Lean's convention `a / 0 = 0` then gives `0`.) -/
noncomputable def corr {n : ℕ} (x y : Fin n → ℝ) : ℝ := Sxy x y / Real.sqrt (Sxy x x * Sxy y y)/-- **The correlation coefficient lies between −1 and 1.** Apply Cauchy–Schwarz to the
deviations `fᵢ = xᵢ − x̄` and `gᵢ = yᵢ − ȳ`: `Sxy² ≤ Sxx · Syy`, so `|Sxy| ≤ √(Sxx · Syy)`. -/
theorem abs_corr_le_one {n : ℕ} (x y : Fin n → ℝ) : |corr x y| ≤ 1 := by
have hcs : Sxy x y ^ 2 ≤ Sxy x x * Sxy y y := by
have := cauchy_schwarz (fun i => x i - mean x) (fun i => y i - mean y)
simpa [Sxy, sq] using this
have habs : |Sxy x y| ≤ Real.sqrt (Sxy x x * Sxy y y) := by
rw [← Real.sqrt_sq_eq_abs]
exact Real.sqrt_le_sqrt hcs
rw [corr, abs_div, abs_of_nonneg (Real.sqrt_nonneg _)]
rcases (Real.sqrt_nonneg (Sxy x x * Sxy y y)).eq_or_lt with h0 | hpos
· rw [← h0, div_zero]
exact zero_le_one
· exact (div_le_one hpos).2 habsTheorem 3: the decomposition of the sum of squared residuals, and its consequences.
/-- The **sum of squared residuals** of the line `y = a + b x`: the residual of the `i`-th
point is the vertical distance `yᵢ − (a + b xᵢ)`. -/
noncomputable def sse {n : ℕ} (x y : Fin n → ℝ) (a b : ℝ) : ℝ := ∑ i, (y i - (a + b * x i)) ^ 2/-- **Where the residuals of a line come from.** If the `x`-values are not all equal
(`Sxx ≠ 0`), then for every line `y = a + bx`,
`SSE(a, b) = Sxx (b − Sxy/Sxx)² + n (ȳ − a − b x̄)² + (Syy − Sxy²/Sxx)`.
Proof: centre the data. With `Xᵢ = xᵢ − x̄` and `Yᵢ = yᵢ − ȳ`, each residual is
`(Yᵢ − b Xᵢ) + (ȳ − a − b x̄)`; the cross terms vanish because `Σ Xᵢ = Σ Yᵢ = 0`; and
`Σ (Yᵢ − bXᵢ)² = Syy − 2b Sxy + b² Sxx` is a quadratic in `b`, completed to a square. -/
theorem sse_eq {n : ℕ} (hn : 0 < n) (x y : Fin n → ℝ) (hx : Sxy x x ≠ 0) (a b : ℝ) :
sse x y a b = Sxy x x * (b - Sxy x y / Sxy x x) ^ 2 + n * (mean y - a - b * mean x) ^ 2 +
(Sxy y y - Sxy x y ^ 2 / Sxy x x) := by
-- centre the data
set X : Fin n → ℝ := fun i => x i - mean x with hXdef
set Y : Fin n → ℝ := fun i => y i - mean y with hYdef
set d := mean y - a - b * mean x with hd
have hX : ∑ i, X i = 0 := sum_sub_mean hn x
have hY : ∑ i, Y i = 0 := sum_sub_mean hn y
have hxx : Sxy x x = ∑ i, X i * X i := rfl
have hxy : Sxy x y = ∑ i, X i * Y i := rfl
have hyy : Sxy y y = ∑ i, Y i * Y i := rfl
-- each residual is `(Yᵢ − b Xᵢ) + d`; expand its square
have expand : sse x y a b = ∑ i, (Y i * Y i - 2 * b * (X i * Y i) + b ^ 2 * (X i * X i) +
2 * d * Y i - 2 * d * b * X i + d ^ 2) :=
sum_congr rfl fun i _ => by simp only [X, Y, d]; ring
rw [expand]
simp only [sum_add_distrib, sum_sub_distrib, ← mul_sum, sum_const, card_univ,
Fintype.card_fin, nsmul_eq_mul]
rw [hX, hY, ← hxx, ← hxy, ← hyy]
field_simp
ring/-- The **least-squares slope** `b̂ = Sxy / Sxx`. -/
noncomputable def slope {n : ℕ} (x y : Fin n → ℝ) : ℝ := Sxy x y / Sxy x x/-- The **least-squares intercept** `â = ȳ − b̂ x̄`, so that the line passes through the point
of means `(x̄, ȳ)`. -/
noncomputable def intercept {n : ℕ} (x y : Fin n → ℝ) : ℝ := mean y - slope x y * mean x/-- **The least-squares line is the best line:** no line `y = a + bx` has a smaller sum of
squared residuals than `y = â + b̂x`. By `sse_eq`, `SSE(a, b)` is a fixed amount plus two
squares (`Sxx > 0` as a sum of squares that is not zero), and both squares vanish at `(â, b̂)`. -/
theorem least_squares {n : ℕ} (hn : 0 < n) (x y : Fin n → ℝ) (hx : Sxy x x ≠ 0) (a b : ℝ) :
sse x y (intercept x y) (slope x y) ≤ sse x y a b := by
have hxx : 0 ≤ Sxy x x := sum_nonneg fun i _ => mul_self_nonneg _
rw [sse_eq hn x y hx, sse_eq hn x y hx]
have h1 : slope x y - Sxy x y / Sxy x x = 0 := by rw [slope]; ring
have h2 : mean y - intercept x y - slope x y * mean x = 0 := by rw [intercept]; ring
rw [h1, h2]
have : 0 ≤ Sxy x x * (b - Sxy x y / Sxy x x) ^ 2 := by positivity
have : 0 ≤ (n : ℝ) * (mean y - a - b * mean x) ^ 2 := by positivity
simp only [ne_eq, OfNat.ofNat_ne_zero, not_false_eq_true, zero_pow, mul_zero, zero_add]
linarith/-- **What is left over.** The least-squares line leaves the residual sum of squares
`Syy − Sxy²/Sxx = Syy (1 − r²)`. Since it cannot be negative, this gives a second proof that
`r² ≤ 1`, and it is `0` exactly when the points lie on a line. -/
theorem min_sse {n : ℕ} (hn : 0 < n) (x y : Fin n → ℝ) (hx : Sxy x x ≠ 0) :
sse x y (intercept x y) (slope x y) = Sxy y y - Sxy x y ^ 2 / Sxy x x := by
rw [sse_eq hn x y hx]
have h1 : slope x y - Sxy x y / Sxy x x = 0 := by rw [slope]; ring
have h2 : mean y - intercept x y - slope x y * mean x = 0 := by rw [intercept]; ring
rw [h1, h2]
ringTheorem 2 lives in probability theory, which Mathlib builds on measure theory. Here X i are random variables on a probability space, MemLp (X i) 2 μ says each has a finite variance, and X i ⟂ᵢ[μ] X j says they are independent:
/-- **The variance of a sample mean is `σ²/n`.** If `X₁, …, Xₙ` are pairwise independent
measurements, each with finite variance `σ²`, then their mean `(X₁ + ⋯ + Xₙ)/n` has variance
`σ²/n`, so its standard deviation is `σ/√n`: four times the sample, half the spread. The proof
applies Mathlib's `ProbabilityTheory.IndepFun.variance_sum` (variances of independent variables
add) and `ProbabilityTheory.variance_const_mul` (`Var(cX) = c² Var(X)`). -/
theorem variance_sample_mean {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} {n : ℕ}
(hn : 0 < n) (X : Fin n → Ω → ℝ) (σ : ℝ) (hL2 : ∀ i, MemLp (X i) 2 μ)
(hind : Set.Pairwise (univ : Finset (Fin n)) fun i j => X i ⟂ᵢ[μ] X j)
(hvar : ∀ i, variance (X i) μ = σ ^ 2) :
variance (fun ω => (1 / n : ℝ) * ∑ i, X i ω) μ = σ ^ 2 / n := by
have hn' : (n : ℝ) ≠ 0 := by exact_mod_cast hn.ne'
rw [variance_const_mul]
have hsum : variance (fun ω => ∑ i, X i ω) μ = ∑ i, variance (X i) μ := by
have e : (fun ω => ∑ i, X i ω) = ∑ i, X i := by
ext ω
rw [Finset.sum_apply]
rw [e]
exact IndepFun.variance_sum (s := univ) (fun i _ => hL2 i) hind
rw [hsum, sum_congr rfl fun i _ => hvar i, sum_const, card_univ, Fintype.card_fin,
nsmul_eq_mul]
field_simpThe central limit theorem, which we used without proof, is in Mathlib — a substantial piece of formalised probability. In its statement, iIndepFun X P says that the measurements are independent, IdentDistrib that they all have the same distribution, gaussianReal 0 v is the normal distribution with mean and variance , and TendstoInDistribution is convergence in distribution:
/-- **The central limit theorem** (in dimension 1). If `X 0, X 1, X 2, …` are independent and
identically distributed, with mean `μ` and finite variance `σ²`, then
`(X 0 + ⋯ + X (n − 1) − n μ) / √n` converges in distribution, as `n → ∞`, to a normal random
variable `Y` with mean `0` and variance `σ²`. This is why sample means are approximately normal and
margins of error use `1.96`. It applies Mathlib's
`ProbabilityTheory.tendstoInDistribution_inv_sqrt_mul_sum_sub`. -/
theorem central_limit_theorem {Ω Ω' : Type*} [MeasurableSpace Ω] [MeasurableSpace Ω']
{P : Measure Ω} [IsProbabilityMeasure P] {P' : Measure Ω'} [IsProbabilityMeasure P']
{X : ℕ → Ω → ℝ} {Y : Ω' → ℝ}
(hY : HasLaw Y (gaussianReal 0 Var[X 0; P].toNNReal) P')
(hX : MemLp (X 0) 2 P) (hindep : iIndepFun X P)
(hident : ∀ i, IdentDistrib (X i) (X 0) P P) :
TendstoInDistribution
(fun (n : ℕ) ω ↦ (√n)⁻¹ * (∑ k ∈ Finset.range n, X k ω - n * P[X 0]))
Filter.atTop Y (fun _ ↦ P) P' :=
tendstoInDistribution_inv_sqrt_mul_sum_sub hY hX hindep hidentWhat is not formalised here: the step from the central limit theorem to the approximate coverage of confidence intervals, and anything about bias or causation — those are not mathematical statements about numbers but claims about how data were produced.
Simulating samples, and testing summaries
"""Sampling variability, margins of error and bias, by simulation.
A town has 20,000 households, of which exactly 7,600 (38%) collect rainwater
in a tank. We pretend not to know this and estimate it from samples. For
simple random samples of size n = 25, 100, 400 and 1,600, two thousand
samples each are drawn (the number of tanks in a simple random sample has a
hypergeometric distribution, which NumPy samples directly). The spread of
the estimates shrinks like 1/sqrt(n), about 95% of the intervals
"estimate +/- margin of error" catch the true value, and a huge voluntary-
response sample is worse than a small random one.
"""
import math
import numpy as np
POPULATION, WITH_TANK = 20000, 7600
P_TRUE = WITH_TANK / POPULATION
def standard_error(p, n, population=POPULATION):
"""SD of the sample proportion for a simple random sample of size n."""
fpc = (population - n) / (population - 1) # finite population correction
return math.sqrt(p * (1 - p) / n * fpc)
def srs_estimates(rng, n, repeats):
"""Sample proportions from `repeats` simple random samples of size n."""
hits = rng.hypergeometric(WITH_TANK, POPULATION - WITH_TANK, n, repeats)
return hits / n
def coverage(estimates, n, z=1.96):
"""Fraction of intervals p_hat +/- z sqrt(p_hat(1-p_hat)/n) containing P."""
margin = z * np.sqrt(estimates * (1 - estimates) / n)
return float(np.mean(np.abs(estimates - P_TRUE) <= margin))
def voluntary_response(rng, responses, p_reply_tank, p_reply_none):
"""Estimate from the first `responses` replies when replying is biased."""
w_tank = P_TRUE * p_reply_tank
w_none = (1 - P_TRUE) * p_reply_none
tanks = rng.binomial(responses, w_tank / (w_tank + w_none))
return tanks / responses
def main():
rng = np.random.default_rng(2024)
print(f"True proportion with a tank: {P_TRUE:.2f} "
f"({WITH_TANK:,} of {POPULATION:,} households)")
print("2,000 simple random samples of each size:")
print(" n mean of estimates SD of estimates formula "
"95% coverage")
for n in (25, 100, 400, 1600):
est = srs_estimates(rng, n, 2000)
print(f" {n:4d} {est.mean():17.4f} {est.std():15.4f} "
f"{standard_error(P_TRUE, n):7.4f} {coverage(est, n):12.3f}")
print("Four times the sample size: half the spread.")
print()
one = srs_estimates(rng, 400, 1)[0]
margin = 1.96 * math.sqrt(one * (1 - one) / 400)
print(f"One survey of 400: estimate {one:.3f}, margin of error "
f"{margin:.3f},")
print(f" interval {one - margin:.3f} to {one + margin:.3f}")
print()
biased = voluntary_response(rng, 5000, 0.6, 0.2)
print("Voluntary response (tank owners reply 3 times as often):")
print(f" 5,000 replies estimate {biased:.3f}; the truth is {P_TRUE:.3f}.")
print(" More data does not cure a biased way of collecting it.")
print()
print("Epistemic status: statistical evidence from one seeded run;")
print("other seeds give slightly different numbers. The formula column")
print("is exact for simple random samples; the coverage of about 95% is")
print("a long-run property of the method, not of any one interval.")
if __name__ == "__main__":
main()Each row quadruples the sample size, and each time the spread of the estimates halves, matching the formula. The coverage column is close to — but any single interval either contains or it does not. And the voluntary-response sample of is far less accurate than a random sample of .
"""Least squares, correlation and their limits: Anscombe's quartet and more.
Francis Anscombe's four data sets (1973) share their means, their variances,
their correlation r = 0.816 and their least-squares line y = 3.00 + 0.500x to
two or three decimals, yet look completely different when plotted - so a
summary is no substitute for a picture. All statistics are computed exactly
with fractions from the lesson's formulas Sxx, Sxy, Syy. Then y = x^2 on a
symmetric range has r = 0 although y is a function of x, and a simulated
town shows ice-cream sales and sea rescues correlated only because both
follow the temperature: the correlation of what is left after removing
temperature's linear effect is close to zero.
"""
import math
import random
from fractions import Fraction
X123 = [10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5]
ANSCOMBE = {
"I": (X123, ["8.04", "6.95", "7.58", "8.81", "8.33", "9.96", "7.24",
"4.26", "10.84", "4.82", "5.68"]),
"II": (X123, ["9.14", "8.14", "8.74", "8.77", "9.26", "8.10", "6.13",
"3.10", "9.13", "7.26", "4.74"]),
"III": (X123, ["7.46", "6.77", "12.74", "7.11", "7.81", "8.84", "6.08",
"5.39", "8.15", "6.42", "5.73"]),
"IV": ([8, 8, 8, 8, 8, 8, 8, 19, 8, 8, 8],
["6.58", "5.76", "7.71", "8.84", "8.47", "7.04", "5.25", "12.50",
"5.56", "7.91", "6.89"]),
}
def sums(x, y):
"""(mean x, mean y, Sxx, Sxy, Syy), exactly if the data are Fractions."""
n = len(x)
mx, my = sum(x, Fraction(0)) / n, sum(y, Fraction(0)) / n
sxx = sum((a - mx) ** 2 for a in x)
sxy = sum((a - mx) * (b - my) for a, b in zip(x, y))
syy = sum((b - my) ** 2 for b in y)
return mx, my, sxx, sxy, syy
def least_squares(x, y):
"""(intercept, slope) of the least-squares line: b = Sxy/Sxx."""
mx, my, sxx, sxy, _ = sums(x, y)
slope = sxy / sxx
return my - slope * mx, slope
def correlation(x, y):
"""r = Sxy / sqrt(Sxx Syy) (a float: the square root is irrational)."""
_, _, sxx, sxy, syy = sums(x, y)
return float(sxy) / math.sqrt(float(sxx) * float(syy))
def residuals(x, y):
"""y minus the least-squares prediction, for each point."""
a, b = least_squares(x, y)
return [v - (a + b * u) for u, v in zip(x, y)]
def confounded_town(rng, days):
"""Temperatures and two quantities that each depend only on them."""
temp = [rng.uniform(15, 35) for _ in range(days)]
ice = [20 * t + rng.gauss(0, 60) for t in temp]
rescues = [0.3 * t + rng.gauss(0, 1.5) for t in temp]
return temp, ice, rescues
def main():
print("Anscombe's quartet (exact arithmetic, rounded for printing)")
print(" set mean x mean y var x var y r line")
for name, (x, ys) in ANSCOMBE.items():
y = [Fraction(v) for v in ys]
mx, my, sxx, _, syy = sums(x, y)
a, b = least_squares(x, y)
print(f" {name:>3} {float(mx):6.2f} {float(my):6.2f} "
f"{float(sxx / 10):6.2f} {float(syy / 10):6.2f} "
f"{correlation(x, y):6.3f} y = {float(a):.2f} + "
f"{float(b):.3f}x")
print("Same summaries; plotted, they look nothing alike.")
print()
xs = list(range(-3, 4))
sxy = sums(xs, [v * v for v in xs])[3]
print(f"y = x^2 for x = -3..3: Sxy = {sxy}, so r = 0 exactly.")
print(" No linear association, yet y is completely determined by x.")
print()
temp, ice, rescues = confounded_town(random.Random(1973), 730)
print("A simulated town, 730 days:")
print(f" r(ice-cream sales, sea rescues) = {correlation(ice, rescues):.2f}")
r_left = correlation(residuals(temp, ice), residuals(temp, rescues))
print(f" after removing temperature's linear effect from both: "
f"r = {r_left:.2f}")
print()
print("Epistemic status: the quartet's statistics are exact computations")
print("from the published data; the town is a simulation built so that")
print("temperature causes both quantities. Correlation alone could not")
print("have told us that.")
if __name__ == "__main__":
main()The four data sets of Anscombe's quartet have the same means, variances, correlation and least-squares line to two or three decimal places. Plotted, the first is a reasonable linear scatter, the second a smooth curve, the third a perfect line with one outlier, and the fourth a vertical stack of points with one far-off point that alone creates the correlation. Summaries are not a substitute for looking at the data.
Explore: lines, bells and coins
Fit a line by eye
The first data set of Anscombe's quartet. Move a and b to make the line fit the points as well as you can.
- y = a + b x
- y = a + b x: y = 2.6
Adjust and until the line looks right, then compare with the least-squares line . Did your line pass near the point of means ? Theorem 3 says the best line always does.
The normal curve and the 1/√n law
Move the sliders and trace along the curves to read off values.
- one measurement (σ = 1)
- average of n measurements (σ/√n)
- Signed area: above the axis counts as positive, below (hatched) as negative
- one measurement (σ = 1): y = 0.242
- average of n measurements (σ/√n): y = 0.108
- Signed area from −1.96 to 1.96 ≈ 0.95 (numerical integration)
The shaded area under the standard normal curve between and is about . The second curve is the normal model for the average of measurements: as you increase it becomes narrower and taller, with standard deviation . At it is half as wide; at , a quarter.
Sampling variability
Flip a fair coin again and again: the proportion of heads settles towards 1/2. This is the law of large numbers.
- this run
- exact probability 1/2
- 1/2 ± 1/√n (about 95% of runs)
486 heads in 1,000 flips: proportion
Simulated0.486
Exact1/2 = 0.5
Simulation of 1,000 flips: 486 heads, proportion 0.486. The exact probability is 1/2.
Evidence, not proofThis is a simulation of 1,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.
Each toss of a fair coin is a sample of size one from a population that is half heads. The running proportion of heads wanders, but mostly stays inside the band , which narrows as the number of tosses grows. Press "New run" a few times.
Exercises
1. Sampling and statistical reasoning
Warm-upHumanA news website asks its readers to click “yes” or “no”: “Should the city ban cars from the old town on Sundays?” readers vote, and say no. What is the main problem with using this to estimate the opinion of all the city's residents?
2. Sampling and statistical reasoning
Warm-upHumanTo estimate the proportion of households in a region that own a bicycle, which survey would you trust more?
3. Sampling and statistical reasoning
CoreHumanA random survey of people has a margin of error of about percentage points. By what factor must the sample size be multiplied to make the margin of error about half as large?
4. Sampling and statistical reasoning
CoreHumanFrom a random sample, a researcher computes a confidence interval for the proportion of adults in a country who use mobile banking: to . Which interpretation is correct (in the usual, frequentist sense)?
5. Sampling and statistical reasoning
CoreHumanFit the least-squares line to the five points . What value of does the line predict at ?
6. Sampling and statistical reasoning
CoreHumanFor a data set, the correlation coefficient is . What can you conclude?
7. Sampling and statistical reasoning
CoreHumanAcross countries, the number of mobile phones per person is strongly positively correlated with life expectancy. Which conclusion is best supported?
8. Sampling and statistical reasoning
StretchHumanIn the proof that , the expansion produces a cross term . Why is it zero?
9. Sampling and statistical reasoning
StretchFormalData are x : Fin n → ℝ and mean x is their mean. Which Lean statement says that the mean minimises the sum of squared deviations?
10. Sampling and statistical reasoning
StretchComputationalWrite fit(xs, ys) returning the pair (a, b) of the least-squares line , and correlation(xs, ys) returning , using , and as in the lesson.
Common misconceptions
Misconception
"A large sample is always better than a small one." Only if both are collected in the same, unbiased way. A biased method gives a precise wrong answer: the Literary Digest's million replies lost to Gallup's much smaller sample. Size reduces chance error; it does nothing about bias.
Misconception
"There is a 95% probability that the true value lies in this interval." In the usual (frequentist) interpretation the true value is fixed and the interval is what varies: describes the long-run success rate of the method. A particular computed interval either contains the true value or it does not. (Bayesian statistics, which treats the unknown value itself as uncertain, makes probability statements of the first kind — but about a differently constructed interval.)
Misconception
"The sample must be a large fraction of the population." The standard error depends on the sample size , not on the population size, as long as the sample is a small part of the population. What matters is how the sample is chosen.
Misconception
"r = 0 means there is no relationship." It means there is no linear relationship. Points on the parabola , placed symmetrically, have .
Misconception
"A strong correlation proves that one thing causes the other." Correlation can come from a confounder, from reverse causation, from selection, or from chance. Causal claims need more: ideally a randomised experiment, or a carefully built case from many observational studies.
Other ways of seeing
Geometry— Correlation is a cosine
Collect the centred data into two vectors in : and . Then , and , so
where is the angle between the two vectors. That is why , and exactly when the vectors point along the same line. Least squares is orthogonal projection: the fitted values are the point of the plane spanned by and closest to , and the residual vector is perpendicular to that plane — Pythagoras in dimensions. See vectors and linear algebra.
Probability— Why the bell curve appears
The central limit theorem says that the average of many independent measurements, each with finite variance, is approximately normally distributed, whatever the distribution of a single measurement — a coin toss, a die, a household's water use. That is why the same number appears in margins of error for very different surveys. Making "approximately" precise, and proving it, is a highlight of probability theory; the Galton board in the Chance Lab is a physical picture of it.
Analysis— Optimisation by completing the square
Every least-squares result in this lesson came from completing the square: a quadratic with equals , so its minimum is at . In calculus the same answers come from setting derivatives to zero: gives . With many variables, least squares becomes the normal equations of statistical inference, and minimising other measures of error leads into optimisation.
History and global context
- Estimating from a sample. In 1802 Pierre-Simon Laplace estimated the population of France by counting the people in a selection of communes, computing their ratio of inhabitants to registered births, and multiplying the number of births in the whole country by this ratio — and he estimated how far off the answer might be.
- Random sampling. In the 1890s the Norwegian statistician Anders Kiær argued for "representative" samples in official statistics; Arthur Bowley used random sampling in a survey of working-class households in Reading, England, in 1912; and in 1934 Jerzy Neyman, working in Poland and then London, gave the theory of stratified random sampling, followed by confidence intervals in 1937.
- India. Prasanta Chandra Mahalanobis founded the Indian Statistical Institute in Kolkata in 1931, ran large crop surveys in Bengal in the late 1930s, and led the creation of the National Sample Survey in 1950, a model for national surveys in many countries.
- Least squares and correlation. Adrien-Marie Legendre published the method of least squares in 1805 to fit the orbits of comets; Carl Friedrich Gauss, who said he had used it since 1795, connected it with the normal distribution in 1809. Francis Galton introduced "regression" (1886), studying the heights of parents and their children, and Karl Pearson gave the correlation coefficient its standard form in 1896.
- Experiments and observation. Ronald Fisher's The Design of Experiments (1935) made randomisation central. The British studies of smoking and lung cancer by Richard Doll and Austin Bradford Hill (from 1950) showed how observational evidence can, with care, support a causal conclusion. Francis Anscombe published his quartet in 1973 to show why data should be plotted.
Further reading
- David Freedman, Robert Pisani and Roger Purves, Statistics (4th edition, 2007) — clear and wise about sampling, regression and causation.
- David Spiegelhalter, The Art of Statistics: Learning from Data (2019).
- Darrell Huff, How to Lie with Statistics (1954) — short, old and still useful.
- F. J. Anscombe, "Graphs in statistical analysis", The American Statistician 27 (1973), 17–21.
- David Salsburg, The Lady Tasting Tea: How Statistics Revolutionized Science in the Twentieth Century (2001) — the history, told through its people.