The law of large numbers, the central limit theorem and confidence intervals
Before this lesson: lesson 02 (expectation, variance and their rules), lesson 03 (the common distributions and moment generating functions) and lesson 04 (the variance of a sum). Time: about 75 minutes, plus the notebook.
Why this matters #
- Model evaluation. A test accuracy of 0.91 on 500 examples is a sample mean of 0/1 values. Its standard error, about , tells you whether 0.91 is really better than another model's 0.90 (here: not clearly).
- A/B tests. The conversion rate of each version of a web page is a sample mean. The usual z-test and its sample-size formula come from the central limit theorem (lesson 12).
- Monte Carlo. A Monte Carlo estimate, such as an expected reward in reinforcement learning or an integral in physics, is a sample mean. Its error is in any dimension (lesson 14).
- Stochastic gradient descent. A minibatch gradient is the mean of per-example gradients. Its noise has standard deviation proportional to (optimization 05).
- Error bars in papers. "Mean ± standard error over 5 seeds" is a confidence interval in disguise, and with only 5 values it needs Student's , not 1.96.
1. Predict first #
2. The picture #
A statistic is a random variable #
Take a population with mean and standard deviation : for example, the time (in minutes) that visitors spend on a web page. Draw a sample of values and compute its mean . A second sample gives a different . The distribution of over many repeated samples is its sampling distribution.
Two facts describe it (we prove them in section 3):
- its centre is the true mean: ;
- its spread is the standard error , much smaller than the spread of the data.
Press "Draw 1,000" several times, then change and draw again. The top chart shows the population density (orange) and the latest sample (blue dots). The bottom chart is the histogram of all sample means (blue) with the normal curve (orange). Notice: the observed SD of the means matches , and for the histogram is close to a bell even for the skewed population.
The law of large numbers: running means settle down #
Flip a coin again and again, and after each flip compute the fraction of heads so far. This running mean jumps a lot at first and then settles near . The band shows how fast: its width falls like , so 100 times more flips give a 10 times narrower band.
Press Play and watch the paths. Each blue line is the running mean of one sequence of flips; path 1 is highlighted. The orange band is . Switch to 20 paths: at every , about 95% of the paths are inside the band. Switch to the die: the band is wider (the die has , the coin ), but it shrinks at the same rate.
The central limit theorem: sums look Gaussian #
Why a bell shape? A Galton board shows the mechanism. Each ball hits pegs and goes left or right with probability at each one. The final bin is the number of right steps: a sum of independent coin flips, so a Binomial(, 1/2) count. Many small independent pushes add up to a bell curve.
Press "Drop 100", then "Drop 1,000 at once". The blue bars count the balls in each bin, the orange ticks are the expected counts from the binomial distribution, and the dashed orange curve is the normal curve with mean and SD . Change the number of rows: the bell gets wider like .
The same happens for sums of almost any variables, not only coin flips. To compare different , we standardise: subtract the mean of the sum and divide by its SD ,
always has mean 0 and variance 1. The central limit theorem says that its shape approaches the standard normal .
Choose a base distribution and increase . The blue histogram shows 20,000 simulated values of ; the orange curve is . The KS distance (the largest gap between the two CDFs) shrinks as grows. Notice: the uniform and the die look Gaussian already at , the exponential needs about , and Bernoulli(0.1) is still lumpy at . Then choose Cauchy: the mean of Cauchy values never gets narrower.
You quadruple the sample size, from to . What happens to the standard error of the mean?
, and . The spread of the data does not change, but the spread of the mean does. "4 times smaller" would hold for the variance , not for the SE.
3. Definitions and main results #
Throughout, are i.i.d. (independent and identically distributed) with mean and variance , and
The mean and the standard error #
Theorem. and .
Proof.
- By linearity of expectation, , so .
- The are independent, so all covariances are 0 and the variances add (lesson 04): .
- with gives .
The standard error of the mean is . In practice is unknown, and we use the estimate , where is the sample standard deviation (with ).
Standard deviation vs standard error. The SD describes the spread of the data; it does not shrink with . The SE describes the spread of the mean; it shrinks. Report the SD when you describe the data, and the SE (or a confidence interval) when you describe how well you know .
Step 2 used only that the variables are uncorrelated. If they are correlated, the variance is larger. With equal pairwise correlation , , which tends to , not to 0.
Markov's and Chebyshev's inequalities #
These two inequalities bound a tail probability with only a mean or a variance.
Markov's inequality. If and , then
Proof.
- For every outcome, . If , the right side is . Otherwise it is ; this is where is used.
- Take expectations of both sides: .
Tight case. with . Then . Equality needs all the mass at and at , so for most distributions Markov is loose.
Chebyshev's inequality. If and , then for every
Proof. Apply Markov to the nonnegative variable with threshold . The events and are the same, so .
Tight case. with probability each, and otherwise (this needs ).
With : . So at least 75% of any distribution lies within 2 SD of the mean, and at least 89% within 3 SD. For a Gaussian the true values are 95.4% and 99.7%.
Modes of convergence #
" goes to " can mean different things. Let and be random variables.
- In probability: for every , . For large , a big error is unlikely.
- Almost surely (a.s.): . Almost every single path converges.
- In distribution: at every where the CDF of is continuous. Only the distributions get close, not the values.
Almost surely implies in probability, and in probability implies in distribution. The converses are false in general.
Two counterexamples
- In distribution, not in probability. Let and for every . Each has exactly the distribution of , so in distribution. But does not shrink.
- In probability, not almost surely. Let be independent. Then , so in probability. But , so by the second Borel–Cantelli lemma for infinitely many , with probability 1: no path converges.
One exception: convergence in distribution to a constant implies convergence in probability.
The law of large numbers #
Theorem (weak law of large numbers, WLLN). If are i.i.d. with mean and finite variance , then in probability: for every , .
Proof.
- and (theorem above).
- Chebyshev applied to : .
- For fixed , the right side goes to 0 as .
What this proof uses, and what it does not give:
- It needs only uncorrelated variables with equal mean and variance. For correlated data (time series, MCMC samples) the variance of the mean can stay large.
- It needs a finite variance. The WLLN also holds with only a finite mean (Khinchin's theorem), with a different proof.
- The strong law of large numbers says more: almost surely, for i.i.d. variables with . Its proof is harder; we only state it.
- Without a mean, there is no law of large numbers. For the Cauchy distribution (density ), . The mean of standard Cauchy variables is again standard Cauchy, for every . Averaging does not help at all.
You average independent standard Cauchy variables. What is the distribution of the average?
Both the LLN and the CLT need a finite mean (and the CLT a finite variance). The Cauchy distribution has neither. One can show (with characteristic functions) that the mean of i.i.d. standard Cauchy variables is standard Cauchy. In the CLT widget the interquartile range of stays 2 for every .
The central limit theorem #
Theorem (CLT). Let be i.i.d. with mean and variance . Then
in distribution, that is, for every , where is the standard normal CDF.
How to use it. For large , approximately
LLN vs CLT. The LLN says where goes (). The CLT says how the error looks on the scale : Gaussian. The data do not become Gaussian; only the mean (or the sum) does.
Proof sketch with moment generating functions
Assume that the MGF is finite near 0 (lesson 03). Standardise so that and .
- . The are independent, so the MGF of the sum is the product: .
- Taylor expansion at 0: .
- Hence , using .
- is the MGF of . If MGFs converge on an interval around 0, the distributions converge (Curtiss' continuity theorem).
With only a finite variance the MGF may not exist. The same steps then work with the characteristic function , which always exists, and Lévy's continuity theorem.
How fast? The Berry–Esseen theorem
If also , then for every
The error of the normal approximation is , and this rate cannot be improved in general. For a fair coin, : the CDF of jumps by about at 0, and the continuous cannot follow the jump.
For Exp(1) data the sum is Gamma(, 1), so the exact distance can be computed:
| 1 | 4 | 16 | 64 | 256 | |
|---|---|---|---|---|---|
| 0.159 | 0.067 | 0.033 | 0.017 | 0.008 | |
| distance | 0.159 | 0.133 | 0.133 | 0.133 | 0.133 |
| Berry–Esseen bound | 1.146 | 0.573 | 0.287 | 0.143 | 0.072 |
From on, times the distance is constant, as the theorem predicts. The bound is valid but about 8 times too large here. Skewed data and rare events (large ) need a much larger .
From random walks to Brownian motion
Let with probability each, and take steps of size every time units. At time you have made steps, so the position has variance . As , the CLT makes the position at time a variable, and the whole path converges to Brownian motion (Donsker's theorem). This is why noise in stochastic differential equations scales like , not (ML for science 12).
When the CLT fails or is slow.
- Infinite variance: Cauchy, or Pareto with tail index below 2. There is no Gaussian limit.
- Strong dependence: a time series with long memory, or samples that share a common error.
- Skewness and rare events: the approximation is poor until is large. For a proportion, a common rule is to want and .
Bound or approximation? For 100 fair coin flips, "60 or more heads" means :
| method | value | kind |
|---|---|---|
| Chebyshev, | 0.25 | bound (always valid) |
| CLT, with | 0.0228 | approximation |
| exact binomial, | 0.0284 | exact |
Chebyshev is valid but 9 times too large. The CLT is close, but it is not a bound: here it is below the truth. Lesson 07 builds bounds that are valid and much tighter.
A coin gives 61 heads in 100 flips. If the coin is fair, how many standard errors is away from ?
Under a fair coin, . So . The CLT gives : unusual for a fair coin. 0.11 is the raw difference, not in units of SE; 0.22 divides by the SD of one flip (0.5) instead of the SE; 44 divides by the variance instead of the SE.
Confidence intervals #
Known . By the CLT, , because for . Read the event the other way round: is the same as . So
is an (approximate) 95% confidence interval for . For a level , replace 1.96 by the quantile (1.645 for 90%, 2.576 for 99%).
What "95%" means. A confidence interval is a procedure: a rule that turns data into an interval. Its coverage is the probability, before you see the data, that the random interval contains the fixed number . "95%" means: if you repeat the whole experiment many times, about 95% of the intervals contain . After you computed one interval, say , nothing is random any more: is in it or not. In the frequentist view is a fixed number, so "" is not a correct statement. (A Bayesian credible interval (lesson 10) does make such a statement, given a prior.)
Press "Draw 100 intervals" a few times. Each bar is one 95% interval from a new data set; it is blue if it contains the true mean (orange line) and magenta if it misses. Then press "Draw 10,000" and read the coverage. With and the estimated SD at , the coverage is about 0.92, not 0.95. Switch to : it goes back to 0.95. Then switch to skewed data: even gives only about 0.90 at .
Unknown : Student's . In practice we replace by the sample SD . This adds uncertainty, and the interval with 1.96 becomes too short for small . For normal data the exact distribution is known:
Student's distribution with degrees of freedom. It is symmetric like , but with heavier tails; as it approaches . The t-interval is
Some 97.5% quantiles: , , , , , and .
For normal data the t-interval has coverage exactly 0.95 for every . For other data it is approximate. A simulation with 200,000 data sets per row (Monte Carlo error about ±0.001) gives:
| data | t-interval | ||
|---|---|---|---|
| normal | 10 | 0.950 | 0.918 |
| normal | 30 | 0.950 | 0.940 |
| exponential (skewed) | 10 | 0.900 | 0.869 |
| exponential (skewed) | 30 | 0.926 | 0.917 |
| exponential (skewed) | 100 | 0.942 | 0.939 |
Two lessons from the table. With small , use , not 1.96. And with skewed data, even under-covers until is large; the bootstrap (lesson 12) is one fix.
From one data set you get the 95% confidence interval for . Which statement is correct?
The 95% is a property of the procedure, before the data are seen. Once computed, either contains the fixed or not. The interval is about , not about the data (that would need the SD, not the SE). A new varies around , not around the old , so the last option is also false.
Intervals for a proportion #
For 0/1 data (clicked or not, correct or not), is the fraction of ones, and . The Wald interval plugs into the SE:
It fails for small or for near 0 or 1. Example: and . With probability you see no success at all; then and the interval is , which misses . The exact coverage (a sum over the binomial PMF) is only 0.635, not 0.95.
The Wilson interval
Instead of plugging into the SE, solve for (a quadratic inequality in ). With , the solution is the Wilson interval
Its centre is pulled towards , and it is never . Exact coverage at :
| Wald | Wilson | |
|---|---|---|
| 0.5 | 0.935 | 0.935 |
| 0.24 | 0.919 | 0.934 |
| 0.02 | 0.635 | 0.922 |
Use Wilson (or the exact Clopper–Pearson interval) by default. In Python:
statsmodels.stats.proportion.proportion_confint(k, n, method="wilson").
Error bars for Monte Carlo, and the delta method #
Monte Carlo. To estimate , draw and average: . This is a sample mean, so the CLT gives the error bar
where is the sample SD of the values . The rate does not depend on the dimension of ; only does. One more correct digit costs 100 times more samples.
The delta method. Often we need a function of a mean: the log-odds of a click rate, the ratio of two means, . If and is differentiable at with , then
so
Why: the first-order Taylor expansion is a linear function of , and a linear function multiplies the SD by . The remainder is of smaller order than . In dimensions the variance is . The delta method is first order: it ignores the bias and skewness that a curved adds.
Answers to section 1. (1) About 0.03: the exact value is 0.0284. The CLT gives , since 60 heads is standard errors above the mean. Chebyshev gives only the bound 0.25. (2) No. The 95% describes how often the procedure covers in repeated experiments. A computed interval contains the fixed or not. (3) 100 times more. The width of the interval is proportional to .
4. Worked example #
(a) A t-interval for exam scores. Eight students get the scores . We want a 95% confidence interval for the mean score of all students who take this exam.
- Mean: .
- Deviations: . Squares: , with sum .
- Sample variance: , so .
- Standard error: .
- degrees of freedom: .
- Half-width: . Interval: .
With 1.96 instead of 2.365 the half-width would be : the interval would be 17% too short, and its coverage for normal data would be below 0.95.
(b) The click rate of a button. A web page shows a new button to visitors; click it.
- Estimate: .
- Standard error: , and this is .
- Half-width: . Wald interval: .
- Wilson interval (formula above): , slightly shifted towards .
Delta method on the log-odds. Logistic regression works with . With we have , so
and with the numbers
. The half-width is , so the 95% interval is . Map both ends back with the logistic function : . This interval is not symmetric around 0.24, and it always stays inside .
How many visitors for ? We want . The worst case is , so : 385 visitors. This is a CLT approximation. Chebyshev gives a guarantee for , but it needs . Lesson 07 finds a guarantee with 738.
(c) What the i.i.d. assumption hides. Suppose the 50 visitors come in groups of friends who influence each other, and every pair of clicks has correlation . Then , against for independent visitors. The true SE is times larger than the formula says.
5. In code #
NumPy and SciPy check the worked example. The notebook for this lesson has these cells and the exercises.
import numpy as np
from scipy import stats
# (a) exam scores: t-interval for the mean
x = np.array([72, 85, 64, 90, 78, 69, 81, 77.])
n, m, s = len(x), x.mean(), x.std(ddof=1)
q = stats.t.ppf(0.975, n - 1)
print(m, round(s, 2), round(s / np.sqrt(n), 2), round(q, 3)) # 77.0 8.52 3.01 2.365
print(np.round(stats.t.interval(0.95, n - 1, loc=m, scale=s / np.sqrt(n)), 2)) # [69.88 84.12]
# (b) 12 clicks out of 50 visitors: Wald interval and the delta method on the log-odds
k, n = 12, 50
p = k / n
se = np.sqrt(p * (1 - p) / n)
print(round(se, 4), np.round([p - 1.96 * se, p + 1.96 * se], 3)) # 0.0604 [0.122 0.358]
theta, se_t = np.log(p / (1 - p)), 1 / np.sqrt(n * p * (1 - p))
lo, hi = theta - 1.96 * se_t, theta + 1.96 * se_t
print(round(theta, 3), round(se_t, 3), np.round(1 / (1 + np.exp(-np.array([lo, hi]))), 3))
# -1.153 0.331 [0.142 0.377]
# (c) Monte Carlo estimate of pi with a CLT error bar
rng = np.random.default_rng(1)
u = rng.random((10_000, 2))
f = 4.0 * (np.sum(u**2, axis=1) <= 1)
print(f.mean(), round(1.96 * f.std(ddof=1) / np.sqrt(len(f)), 3)) # 3.1564 0.032 (one run)
# (d) coverage of the Wald interval for a rare event, exact
z = stats.norm.ppf(0.975)
k = np.arange(51); ph = k / 50
cover = np.abs(ph - 0.02) <= z * np.sqrt(ph * (1 - ph) / 50)
print(round(stats.binom.pmf(k, 50, 0.02)[cover].sum(), 3)) # 0.635, not 0.95
In (c) the error bar contains . The SD of one value of is , so every run of 10,000 points has a half-width close to .
6. Where it shows up #
- Comparing models. Two classifiers with test accuracies 0.912 and 0.905 on 2,000 examples differ by 0.007. Each accuracy has a standard error of about 0.006, so the difference is not clear. Report intervals, and use a paired test on the same examples (lesson 11).
- Seeds in deep learning. Results over 3–5 random seeds are a tiny sample. Use the quantile ( for 5 seeds), not 1.96, or report all values.
- A/B tests. The sample size per arm, for a difference at 5% level and 80% power, comes from the CLT (lesson 12).
- Monte Carlo and MCMC. Error bars for integrals and expected rewards; for correlated MCMC samples, is replaced by an effective sample size (lesson 15).
- Ensembles and averaging in science. Averaging independent sensor readings or ensemble members reduces the noise by , but a shared error (the same model physics, the same calibration) does not average out.
- Batch size in SGD. The gradient noise falls like , which is behind heuristics that scale the learning rate with the batch size.
7. Common mistakes #
- Mixing up SD and SE. The SD of the data does not shrink with ; the SE of the mean does. Error bars that use the SD are not confidence intervals for the mean.
- "The data become Gaussian for large ." No. The CLT is about the distribution of the mean (or sum). A histogram of 10,000 exponential values is still exponential.
- "There is a 95% probability that is in this interval." For a computed confidence interval this is wrong; the 95% belongs to the procedure.
- Using 1.96 with a small sample. With and estimated , the coverage is about 0.92. Use .
- Using the Wald interval for rare events. At , its coverage is 0.635. Use Wilson.
- Treating the CLT as a bound. It is an approximation with error ; for 100 coin flips it was below the exact tail. Use a concentration inequality when you need a guarantee.
- Forgetting dependence. needs uncorrelated data. Time series, MCMC samples, users in the same group, or repeated measurements of one patient break it.
- Markov on a variable that can be negative. Markov needs . Apply it to or instead.
8. Check yourself #
- and . Bound . Can the bound be reached?
Answer
Markov gives . Yes: with has mean 3 and . - A die is rolled 100 times. Use Chebyshev to bound .
Answer
One roll has . So and . (The CLT gives about .) - 25 measurements have and . Give a 95% confidence interval for ().
Answer
, so . - A Monte Carlo estimate with samples has the error bar . How many samples give ?
Answer
The error bar must shrink by 4, so must grow by : 160,000 samples. - is the mean of i.i.d. draws with and . Approximate the SD of .
Answer
Delta method with , : . - Independent . Does in probability? Almost surely?
Answer
Both. In probability: . Almost surely: , so by the first Borel–Cantelli lemma only finitely many equal 1, with probability 1. Compare , which fails almost surely.
What is the standard error of the mean of i.i.d. values with SD ?
; estimated by .
State Chebyshev's inequality.
for every , if the variance is finite.
State the weak law of large numbers and the tool of its short proof.
For i.i.d. data with finite variance, in probability. Proof: Chebyshev with .
State the central limit theorem with its assumptions.
If are i.i.d. with mean and variance , then in distribution.
Give the 95% confidence interval for a mean with unknown .
, with Student's quantile for degrees of freedom.
What does the "95%" of a confidence interval mean?
The procedure contains the true parameter in about 95% of repeated experiments; one computed interval either contains it or not.
Why does the Wald interval fail for , ?
With probability there is no success; then and the interval is . Its coverage is 0.635.
A Monte Carlo error bar is too wide by a factor 10. How many more samples do you need?
100 times more, because the error is proportional to .
State the delta method for .
; more precisely .
Why is the mean of Cauchy samples useless?
The Cauchy distribution has no mean; the mean of standard Cauchy values is again standard Cauchy, for every .
9. Interview angle #
- "State the CLT. What can break it?" — i.i.d. with finite variance; then the standardised mean tends to . It breaks with infinite variance (Cauchy, heavy tails), strong dependence, and it is slow for skewed data and rare events.
- "LLN versus CLT?" — The LLN says . The CLT says the error is approximately .
- "How many samples to estimate a probability within ±1% at 95%?" — Worst case : .
- "What does a 95% confidence interval mean?" — The procedure covers the true value in 95% of repeated experiments. It is not a 95% probability for the one interval you computed.
- "Why is the Monte Carlo error independent of the dimension?" — The estimate is a sample mean with SE ; the dimension enters only through .
- "Your model gets 0.80 accuracy on 400 test examples. Error bar?" — , so about at 95%.
10. Practice #
The notebook for this lesson has five exercises, each with a check cell and a folded solution:
- Running means of coin flips, and the fraction of paths inside the band .
- The KS distance of standardised exponential means to , and why stays constant.
- A t-based
mean_confidence_intervaland its coverage for normal and skewed data. - Wald and Wilson intervals for a proportion, and their exact coverage at .
- A Monte Carlo estimate of with a CLT error bar, and the coverage of that error bar.
11. Watch and read #
- Joseph Blitzstein and Jessica Hwang, Introduction to Probability, 2nd edition (free PDF from the authors): §10.1 (inequalities), §10.2 (law of large numbers), §10.3 (central limit theorem), §10.4 (chi-square and Student's ).
- Larry Wasserman, All of Statistics: ch. 5 (convergence of random variables, the delta method) and ch. 6 (confidence intervals).
- Art Owen, Monte Carlo theory, methods and examples, ch. 2: the error of simple Monte Carlo, estimating probabilities, and intervals for rare events.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.