Sign in

Law of large numbers

Law of large numbers and central limit theorem

Simulation of the two limit theorems for sample means: the mean settles on the true mean, and its fluctuations become normal.

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

  1. Pick a distribution whose mean μ\mu and variance σ2\sigma^{2} are known: exponential, uniform, Bernoulli or normal.
  2. Draw a long sequence and compute the mean of the first kk draws for every kk. Plotting this running mean shows it settling on μ\mu.
  3. Repeat a smaller experiment many times: draw nn values, average them, and keep the average. This gives many independent sample means.
  4. Count how often a sample mean lands further than some ε\varepsilon from μ\mu, and compare that share with the Chebyshev bound.
  5. Standardize each sample mean by subtracting μ\mu and dividing by σ/n\sigma / \sqrt{n}.
  6. 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 1/n1 / \sqrt{n}, which is slow. Ten times the accuracy costs a hundred times the data.
  • The normal approximation is poor for small nn 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

IfUse instead
The data are heavy-tailed, with no finite varianceThe median and quantiles, or a bootstrap, in place of normal-based intervals
The sample is smallAn exact method or a t distribution, as in the lessons on estimation and test statistics
Observations depend on each other over timeTime series analysis or Markov chains

Math foundations

  1. The sample mean

    Xˉn=1n∑i=1nXi\bar{X}_n = \frac{1}{n} \sum_{i=1}^{n} X_i

    The average of nn independent draws from the same distribution. It is itself a random quantity: a new sample gives a new value.

  2. Its mean and variance

    E[Xˉn]=μ,Var⁡(Xˉn)=σ2n\mathbb{E}[\bar{X}_n] = \mu, \qquad \operatorname{Var}(\bar{X}_n) = \frac{\sigma^{2}}{n}

    The sample mean is centred on the true mean and its variance falls in proportion to 1/n1/n. The square root, σ/n\sigma / \sqrt{n}, is called the standard error.

  3. Chebyshev's bound

    P(∣Xˉn−μ∣≥ε)≤σ2n ε2P\big(|\bar{X}_n - \mu| \ge \varepsilon\big) \le \frac{\sigma^{2}}{n\,\varepsilon^{2}}

    A guarantee that uses only the variance. For any fixed ε\varepsilon the right side goes to zero as nn grows, which proves the next line.

  4. Law of large numbers

    lim⁡n→∞P(∣Xˉn−μ∣>ε)=0for every ε>0\lim_{n \to \infty} P\big(|\bar{X}_n - \mu| > \varepsilon\big) = 0 \quad \text{for every } \varepsilon > 0

    The weak form of the law. However small a margin you choose, the chance that the sample mean misses μ\mu by more than that margin vanishes.

  5. Central limit theorem

    Zn=n (Xˉn−μ)σ → d  N(0,1)Z_n = \frac{\sqrt{n}\,\big(\bar{X}_n - \mu\big)}{\sigma} \ \xrightarrow{\ d\ }\ \mathcal{N}(0, 1)

    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.

  6. Kolmogorov-Smirnov distance

    D=sup⁡z ∣Fm(z)−Φ(z)∣D = \sup_{z}\,\big|F_m(z) - \Phi(z)\big|

    The largest vertical gap between the empirical cumulative curve of mm standardized means and the normal curve. The template uses it to put a number on how normal the means look.

Symbols

XiX_i
the ii-th draw
Xˉn\bar{X}_n
the mean of nn draws
nn
the sample size (sample_size in the config)
μ\mu
the true mean of the distribution
σ2\sigma^{2}
the true variance of the distribution
ε\varepsilon
a chosen margin of error
ZnZ_n
the standardized sample mean
N(0,1)\mathcal{N}(0, 1)
the standard normal distribution
FmF_m
the empirical cumulative distribution of mm standardized means
Φ\Phi
the standard normal cumulative distribution function
mm
the number of sample means (n_trials in the config)

Worked by hand

Use the default setting: exponential draws with rate 1, so μ=1\mu = 1 and σ2=1\sigma^{2} = 1, averaged in samples of n=50n = 50. How likely is a sample mean to miss by more than ε=0.5\varepsilon = 0.5?

σn=150≈0.141\frac{\sigma}{\sqrt{n}} = \frac{1}{\sqrt{50}} \approx 0.141
P(∣Xˉ50−1∣≥0.5)≤150×0.52=0.08P\big(|\bar{X}_{50} - 1| \ge 0.5\big) \le \frac{1}{50 \times 0.5^{2}} = 0.08
εσ/n=0.50.141≈3.5\frac{\varepsilon}{\sigma / \sqrt{n}} = \frac{0.5}{0.141} \approx 3.5

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 less
Read 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

  1. Why does the standard error fall like 1/n1 / \sqrt{n} and not like 1/n1 / n?
    A way to think about it

    Variances of independent draws add, so the variance of the sum grows like nn. Follow what dividing the sum by nn does to the variance, then take the square root.

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

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

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

  5. 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 0.87/m0.87 / \sqrt{m}. A value near the floor cannot be told apart from a true normal.