Central Limit Theorem in Python: Simulate and Plot It

Simulate the central limit theorem with NumPy: draw many samples from a skewed population, plot the histogram of their means and compare it with the normal curve the theorem predicts.

To simulate the central limit theorem in Python, draw many samples with a NumPy Generator, take the mean of each sample, and plot a histogram of those means. Even when the population is skewed, the means pile up in a bell curve centered on the population mean, with a standard deviation of sigma / sqrt(n). Overlaying norm.pdf from scipy shows how close the match is.

This post was run with NumPy 2.5, scipy 1.18 and Matplotlib 3.11.

Quick Example

The population here is exponential with a mean of 2, which is strongly right-skewed. We take 10,000 samples of 30 values each and average each sample.

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

rng = np.random.default_rng(42)
mu = sigma = 2.0                      # an exponential distribution has mean == sd == scale
n, reps = 30, 10_000

samples = rng.exponential(scale=mu, size=(reps, n))   # 10,000 samples of 30 values
means = samples.mean(axis=1)                           # one mean per sample

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.hist(means, bins=50, density=True, color="#8d6a9f", alpha=0.8, label="10,000 sample means")

x = np.linspace(means.min(), means.max(), 300)
ax.plot(x, norm.pdf(x, loc=mu, scale=sigma / np.sqrt(n)), color="#1b1b1b", lw=2,
        label="Normal(mu, sigma / sqrt(n))")
ax.set(title="Means of samples of 30 from a skewed population",
       xlabel="Sample mean", ylabel="Density")
ax.legend()
plt.show()

Histogram of 10,000 sample means centered near 2 with a normal curve laid over it

The means are centered at 2.00 (the average of the 10,000 means is 1.997), and their standard deviation is 0.365, against a theoretical 2 / sqrt(30) = 0.365. About 95.2% of the means fall within 1.96 standard errors of 2, close to the 95% a normal curve predicts. The match is not perfect: the histogram still leans right (skewness 0.37, against 2.02 for single draws from the population), which is what n=30 leaves behind for a distribution this skewed.

How the means change as the sample size grows

With n=1 each "mean" is a single draw, so you just see the population. Taking reps samples of each size and plotting them side by side shows the shape changing:

sizes = [1, 2, 5, 30]
fig, axes = plt.subplots(1, 4, figsize=(12, 3.2), sharey=True)
for ax, size in zip(axes, sizes):
    m = rng.exponential(mu, size=(reps, size)).mean(axis=1)
    ax.hist(m, bins=40, density=True, color="#2a9d8f", alpha=0.85)
    ax.set_title(f"n = {size}")
    ax.set_xlim(0, 8)
axes[0].set_ylabel("Density")
fig.supxlabel("Sample mean")
fig.tight_layout()
plt.show()

Four histograms of sample means for n equal to 1, 2, 5 and 30, going from a steep right-skewed shape to a narrow bell curve

At n=1 the histogram is the skewed exponential itself. By n=5 the peak has moved away from zero and the shape is lopsided but recognizable, and by n=30 it is a narrow bell centered on 2. Note that the x-axis is fixed at 0 to 8 for all four panels, so the narrowing is real and not a rescaling.

Does it work for other populations?

The theorem does not care what the population looks like, as long as it has a finite variance. Here are three very different ones: a flat uniform distribution, the skewed exponential, and a two-humped mixture of two normals. The top row is single draws (n=1) and the bottom row is the mean of 30:

populations = {
    "Uniform(0, 1)": lambda size: rng.uniform(0, 1, size),
    "Exponential": lambda size: rng.exponential(2, size),
    "Two humps": lambda size: np.where(rng.random(size) < 0.5,
                                       rng.normal(-2, 0.7, size), rng.normal(3, 1.0, size)),
}

fig, axes = plt.subplots(2, 3, figsize=(11, 5.5))
colors = ["#e76f51", "#8d6a9f", "#264653"]
for col, ((name, draw), color) in enumerate(zip(populations.items(), colors)):
    axes[0, col].hist(draw(100_000), bins=60, density=True, color=color, alpha=0.8)
    axes[1, col].hist(draw((reps, 30)).mean(axis=1), bins=50, density=True, color=color, alpha=0.8)
    axes[0, col].set_title(name)
axes[0, 0].set_ylabel("One draw (n = 1)")
axes[1, 0].set_ylabel("Mean of 30")
fig.tight_layout()
plt.show()

Top row shows a flat, a skewed and a two-humped population; bottom row shows the means of 30 draws from each, all bell shaped

All three bottom-row histograms are bell shaped, even though the top row is flat, skewed and bimodal. The center moves to each population's mean (0.5, 2 and 0.5), and the spread is much narrower than the top row. The exponential column is the slowest to look symmetric, since it starts out the most skewed.

How fast does the spread of the means shrink?

The standard deviation of the sample means (the standard error) is sigma / sqrt(n). To check it, simulate several sample sizes and compare the measured spread with the formula on log-log axes, where 1 / sqrt(n) is a straight line:

ns = np.array([1, 2, 5, 10, 30, 100, 300, 1000])
measured = np.array([rng.exponential(mu, size=(2_000, k)).mean(axis=1).std() for k in ns])
theory = sigma / np.sqrt(ns)

fig, ax = plt.subplots(figsize=(7, 4.5))
ax.loglog(ns, theory, color="#1b1b1b", lw=2, label="sigma / sqrt(n)")
ax.loglog(ns, measured, "o", color="#e76f51", ms=8, label="Simulated")
ax.set(xlabel="Sample size n", ylabel="Standard deviation of the sample mean",
       title="The standard error shrinks with the square root of n")
ax.legend()
plt.show()
print(np.round(measured, 3))

Log-log plot of simulated standard error against sample size, with points sitting on the sigma over square root of n line

[1.976 1.451 0.879 0.637 0.36  0.201 0.113 0.063]

The formula gives 2.00, 1.41, 0.89, 0.63, 0.37, 0.20, 0.12 and 0.063 for these sizes, and the simulated values match to within sampling noise (each uses 2,000 samples). To halve the standard error you need four times as many observations, which is why precision gets expensive. The same sigma / sqrt(n) is the width behind confidence intervals.

When does the central limit theorem fail?

It needs a finite variance. The Cauchy distribution has none, so averaging does not help at all. The spread (interquartile range) of the means stays the same however large the samples get, while a well-behaved population shrinks as 1 / sqrt(n):

for k in [10, 100, 1000]:
    cauchy = np.percentile(rng.standard_cauchy((2_000, k)).mean(axis=1), [25, 75])
    expo = np.percentile(rng.exponential(mu, (2_000, k)).mean(axis=1), [25, 75])
    print(f"n={k:>4}  Cauchy IQR of means: {np.diff(cauchy)[0]:.2f}   Exponential IQR: {np.diff(expo)[0]:.2f}")
n=  10  Cauchy IQR of means: 2.06   Exponential IQR: 0.84
n= 100  Cauchy IQR of means: 1.92   Exponential IQR: 0.28
n=1000  Cauchy IQR of means: 1.99   Exponential IQR: 0.09

The exponential IQR falls by about a factor of three for every tenfold increase in n (0.84, 0.28, 0.09), which is the 1 / sqrt(10) rate. The Cauchy IQR stays near 2 whether you average 10 values or 1,000. The mean of a Cauchy sample is itself Cauchy distributed, so there is no bell curve to converge to. Real data with very heavy tails can need far more than 30 observations before the mean looks normal.

Central limit theorem vs law of large numbers

Law of large numbers Central limit theorem
Says The sample mean gets close to the population mean The sample mean is approximately normal around it
Describes Where the mean ends up The shape and spread of the error
Spread of the mean Shrinks toward 0 sigma / sqrt(n)
Needs A finite mean A finite mean and variance

Practical Tips

  • Simulate reps samples at once. rng.exponential(mu, size=(reps, n)).mean(axis=1) is far faster than a Python loop.
  • How big is big enough? For mild skew, n=30 is usually fine, as the plots above show. Heavier skew or outliers need more, so check with a QQ plot of the means.
  • The theorem is about means (and sums), not about the raw data. A sample of 1,000 skewed values is still skewed.
  • Real data is not independent. Daily stock returns are correlated in volatility, so aggregating them approaches a bell curve more slowly than the theorem suggests.

Similar Topics