Overview
Average more and more independent draws from the same distribution and the average stops moving around: it closes in on the true mean. That is the law of large numbers. The central limit theorem describes the error that remains. Whatever the shape of the original distribution, as long as it has a finite variance, the average of many draws is spread around the true mean in a bell curve whose width shrinks like one over the square root of the sample size. So four times the data buys only half the error.
A short history
Jacob Bernoulli proved the first law of large numbers for repeated trials, published in Ars Conjectandi in 1713. Abraham de Moivre showed in 1733 that the binomial distribution approaches the normal curve, and Pierre-Simon Laplace extended that result to sums in general around 1810. Aleksandr Lyapunov and Jarl Lindeberg gave rigorous general proofs in the early 1900s. Together the two theorems justify estimating from samples.
How it works
- Pick a distribution whose mean and variance are known: exponential, uniform, Bernoulli or normal.
- Draw a long sequence and compute the mean of the first draws for every . Plotting this running mean shows it settling on .
- Repeat a smaller experiment many times: draw values, average them, and keep the average. This gives many independent sample means.
- Count how often a sample mean lands further than some from , and compare that share with the Chebyshev bound.
- Standardize each sample mean by subtracting and dividing by .
- Measure how close the standardized means are to a standard normal with the Kolmogorov-Smirnov distance, the largest gap between the two cumulative curves.
Watch out for
- Both theorems need independent draws with a finite variance. For heavy-tailed data such as the Cauchy distribution the average never settles.
- The error shrinks like , which is slow. Ten times the accuracy costs a hundred times the data.
- The normal approximation is poor for small when the source is skewed. Means of five exponential draws are still clearly lopsided.
- The Chebyshev bound holds for every distribution, so it is loose. Do not read it as an estimate of the actual probability.
- The law of large numbers does not say that a run of low values is balanced by high ones later. Early deviations are diluted, not corrected.
Use cases
When to use it
Deciding how much data an estimate needs, justifying error bars and confidence intervals on an average, and understanding why minibatch gradients and Monte Carlo estimates work.
In industry
- Polling
- Survey firms rely on the central limit theorem to state a margin of error around a sample share.
- Insurance and gaming
- Insurers and casinos price on averages: over many independent policies or bets the average result settles close to its expected value.
- Online experimentation
- A/B tests compare mean metrics between groups with normal-based intervals, which is valid because the group means are averages of many users.
Choosing it: what must hold
- Observations that are independent, or only weakly dependent, and drawn from the same distribution.
- A finite mean for the law of large numbers, and a finite variance for the central limit theorem.
- A sample large enough for the limit to be a fair approximation. Skewed data need more observations.
When to choose something else
| If | Use instead |
|---|---|
| The data are heavy-tailed, with no finite variance | The median and quantiles, or a bootstrap, in place of normal-based intervals |
| The sample is small | An exact method or a t distribution, as in the lessons on estimation and test statistics |
| Observations depend on each other over time | Time series analysis or Markov chains |
Math foundations
The sample mean
The average of independent draws from the same distribution. It is itself a random quantity: a new sample gives a new value.
Its mean and variance
The sample mean is centred on the true mean and its variance falls in proportion to . The square root, , is called the standard error.
Chebyshev's bound
A guarantee that uses only the variance. For any fixed the right side goes to zero as grows, which proves the next line.
Law of large numbers
The weak form of the law. However small a margin you choose, the chance that the sample mean misses by more than that margin vanishes.
Central limit theorem
After rescaling by the standard error, the distribution of the sample mean approaches the standard normal. The arrow means convergence in distribution: the cumulative curves get closer.
Kolmogorov-Smirnov distance
The largest vertical gap between the empirical cumulative curve of standardized means and the normal curve. The template uses it to put a number on how normal the means look.
Symbols
- the -th draw
- the mean of draws
- the sample size (sample_size in the config)
- the true mean of the distribution
- the true variance of the distribution
- a chosen margin of error
- the standardized sample mean
- the standard normal distribution
- the empirical cumulative distribution of standardized means
- the standard normal cumulative distribution function
- the number of sample means (n_trials in the config)
Worked by hand
Use the default setting: exponential draws with rate 1, so and , averaged in samples of . How likely is a sample mean to miss by more than ?
Chebyshev guarantees at most 8%. The central limit theorem says a miss of 0.5 is about 3.5 standard errors, which a normal variable exceeds roughly 0.05% of the time. The bound is safe but far from tight.
Visual example
Loading the example.
Try this
- Set n to 1 to see the raw exponential shape, then slide to 30 and watch it turn into a bell.
- Go from n = 25 to n = 100: the spread halves.
- Choose the Bernoulli draw with a small n. The means can only take a few values, and D stays large until n grows.
Code sample
from impl import LawOfLargeNumbers, ks_distance_to_normal
from config import LawOfLargeNumbersConfig
lln = LawOfLargeNumbers(LawOfLargeNumbersConfig(distribution="exponential", param=2.0))
path = lln.running_mean() # (10000,), ends near the true mean 0.5
z = lln.standardized_means(sample_size=50) # (2000,), close to N(0, 1)
ks_distance_to_normal(z) # small, about 0.03
lln.chebyshev_bound(eps=0.2), lln.deviation_probability(eps=0.2) # bound 0.125, observed far lessRead the implementation (90 lines)
"""Law of large numbers and central limit theorem, by simulation.
Draws from a distribution with known mean and variance and shows the two limit theorems at work: the running
mean settles on the true mean (LLN), and standardized sample means look standard normal (CLT). The Chebyshev
bound and the Kolmogorov-Smirnov distance to the normal CDF put numbers on both.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import LawOfLargeNumbersConfig
except ImportError: # run from the template's own folder
from config import LawOfLargeNumbersConfig
def ks_distance_to_normal(z) -> float:
"""Kolmogorov-Smirnov distance between the empirical CDF of z, array (n,), and the standard normal CDF.
0 means a perfect match; a sample of n true normal draws gives about 0.87 / sqrt(n) on average.
"""
z = np.sort(np.asarray(z, dtype=float).ravel())
n = z.size
if n == 0:
raise ValueError("z is empty")
cdf = np.array([0.5 * (1.0 + math.erf(v / math.sqrt(2.0))) for v in z])
upper = np.arange(1, n + 1) / n - cdf
lower = cdf - np.arange(0, n) / n
return float(max(upper.max(), lower.max()))
class LawOfLargeNumbers:
"""Simulation of sample means for one of four distributions with known moments."""
def __init__(self, config: LawOfLargeNumbersConfig | None = None) -> None:
self.config = config or LawOfLargeNumbersConfig()
self.rng = np.random.default_rng(self.config.seed)
def true_mean(self) -> float:
d, p = self.config.distribution, self.config.param
return {"exponential": 1.0 / p, "uniform": p / 2.0, "bernoulli": p, "normal": 0.0}[d]
def true_variance(self) -> float:
d, p = self.config.distribution, self.config.param
return {"exponential": 1.0 / p**2, "uniform": p**2 / 12.0, "bernoulli": p * (1.0 - p), "normal": p**2}[d]
def sample(self, shape) -> np.ndarray:
"""Independent draws of the configured distribution, array of the given shape."""
d, p = self.config.distribution, self.config.param
if d == "exponential":
return self.rng.exponential(1.0 / p, size=shape)
if d == "uniform":
return self.rng.uniform(0.0, p, size=shape)
if d == "bernoulli":
return (self.rng.random(size=shape) < p).astype(float)
return self.rng.normal(0.0, p, size=shape)
def running_mean(self, n_samples: int | None = None) -> np.ndarray:
"""Mean of the first k draws for k = 1..n, array (n,). The LLN says it converges to `true_mean()`."""
n = n_samples or self.config.n_samples
return np.cumsum(self.sample(n)) / np.arange(1, n + 1)
def sample_means(self, sample_size: int | None = None, n_trials: int | None = None) -> np.ndarray:
"""n_trials independent means, each of sample_size draws. Returns array (n_trials,)."""
size = sample_size or self.config.sample_size
trials = n_trials or self.config.n_trials
return self.sample((trials, size)).mean(axis=1)
def standardized_means(self, sample_size: int | None = None, n_trials: int | None = None) -> np.ndarray:
"""sqrt(n) (mean - mu) / sigma for each trial, array (n_trials,). The CLT says these tend to N(0, 1)."""
size = sample_size or self.config.sample_size
means = self.sample_means(size, n_trials)
return math.sqrt(size) * (means - self.true_mean()) / math.sqrt(self.true_variance())
def deviation_probability(self, eps: float, sample_size: int | None = None, n_trials: int | None = None) -> float:
"""Share of trials whose sample mean is further than eps from the true mean."""
means = self.sample_means(sample_size, n_trials)
return float(np.mean(np.abs(means - self.true_mean()) > eps))
def chebyshev_bound(self, eps: float, sample_size: int | None = None) -> float:
"""Upper bound on P(|mean - mu| > eps): sigma^2 / (n eps^2), capped at 1."""
if eps <= 0:
raise ValueError("eps must be positive")
size = sample_size or self.config.sample_size
return min(1.0, self.true_variance() / (size * eps * eps))
def standard_error(self, sample_size: int | None = None) -> float:
"""Standard deviation of the sample mean: sigma / sqrt(n)."""
return math.sqrt(self.true_variance() / (sample_size or self.config.sample_size))- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Create LawOfLargeNumbers with the default config and look at running_mean() at positions 10, 100, 1000 and 10000. Compare deviation_probability(0.5) with chebyshev_bound(0.5). Then call ks_distance_to_normal on standardized_means(sample_size=2), then with 10, then with 200, and describe how the distance changes.
Check on learning
- Why does the standard error fall like and not like ?
A way to think about it
Variances of independent draws add, so the variance of the sum grows like . Follow what dividing the sum by does to the variance, then take the square root.
- Switch the distribution to bernoulli with param 0.01 and keep sample_size at 50. Would you trust a normal approximation for the sample mean? Why not?
A way to think about it
Count how many successes a sample of 50 is expected to contain. A mean that can only be 0, 0.02, 0.04 and so on, mostly 0, does not look like a bell.
- A gambler has lost ten fair bets in a row and says a win is now due because of the law of large numbers. What is the mistake?
A way to think about it
The law is about the average of many future draws swamping the past. Ask whether the next toss knows anything about the previous ten.
- The measured share of misses is far below the Chebyshev bound. Is the bound wrong, and when would it be close to tight?
A way to think about it
A bound that must hold for every distribution with that variance has to cover the worst case. Think of a distribution that puts its mass exactly at the margin.
- With 2000 trials, even perfectly normal data gives a Kolmogorov-Smirnov distance of about 0.02. How does that change your reading of a measured distance of 0.025?
A way to think about it
The distance has a noise floor of roughly . A value near the floor cannot be told apart from a true normal.