Khush Shah

Central Limit Theorem

Khush Shah, Kajal Panchal 26 min read Statistics, Python, Tutorials
Note

This is a combined work of Khush Shah and Kajal Panchal.

Most confidence intervals for a mean, and most A/B tests that compare two averages, lean on the central limit theorem: they treat the sample mean as normally distributed even when the data are nothing like normal. Here we test that by experiment, drawing thousands of sample means from three simulated populations and from a heavily skewed real dataset, and putting the normal curve the theorem predicts on top of each one to see how soon the two agree; for the real data, the answer is "not soon".

Abstract

According to the central limit theorem, the sample average has approximately Normal distribution for large sample sizes. The following exercise is to experimentally verify this theorem on a simulated as well as a real dataset. 1000 random samples are drawn from 3 different distributions (Uniform, Normal and Laplace) for each of the sample sizes 2, 5, 10, 30, 100 and 500, using a seeded NumPy random generator. To verify it on a real data set, Global YouTube Statistics 2023 was taken from Kaggle, and 5,000 samples of sizes 10, 30, 100, 300 and 900 are drawn from its 995 subscriber counts, with and without replacement. Sample means are calculated, and their distribution for each data set and sample size is compared with the normal distribution the theorem predicts, using histograms with the normal density drawn on top, QQ-plots, and the skewness and excess kurtosis of the means. In the case of simulated data, the sample means of the Normal population are exactly normal for every sample size, and those of the Uniform and Laplace populations are already very close to normal at n = 10. In the case of the YouTube statistics dataset, whose subscriber counts have a skewness of 5.5, normality emerges slowly: the skewness of the sample mean falls only like $5.5/\sqrt{n}$, so the sample means are still visibly right-skewed at n = 100 (skewness about 0.5 to 0.6 with either scheme), and the two sampling schemes give almost the same shape. Sampling without replacement mainly reduces the spread, by the finite-population correction $\sqrt{(N-n)/(N-1)}$, which takes 5% off at n = 100 and a lot only when n is a sizeable fraction of the N = 995 channels.

Introduction

Central Limit Theorem

Let $X_1, X_2, \dots, X_n$ be IID random variables with mean $\mu$ and finite variance $\sigma^2$. Let $\bar{X}_n = \frac{1}{n} \sum_{i=1}^{n} X_i$ and

$$Z_n = \frac{\bar{X}_n - \mu}{\sigma/\sqrt{n}} = \frac{\sqrt{n}\,(\bar{X}_n - \mu)}{\sigma}.$$

Then $Z_n$ converges in distribution to $N(0, 1)$ as $n \to \infty$, written $Z_n \xrightarrow{d} N(0, 1)$. In other words, for every $z$,

$$\begin{aligned} \lim_{n \to \infty} P(Z_n \leq z) &= \Phi(z) \\ &= \int_{-\infty}^{z} \frac{1}{\sqrt{2\pi}}\, e^{-x^2/2}\, dx, \end{aligned}$$

where $\Phi(z)$ is the CDF of the standard normal distribution.

Convergence in distribution is a statement about these probabilities, which is why, using the above theorem, probability statements about the sample mean can be approximated using a normal distribution: for large $n$, $P(\bar{X}_n \le x) \approx \Phi\big(\sqrt{n}\,(x - \mu)/\sigma\big)$. It's the probability statements that are being approximated, not the random variable itself. For a fixed $n$, $\bar{X}_n$ is exactly normal only when the $X_i$ are normal to begin with.

Samples and Distributions

To verify the central limit theorem, in this exercise, we have used two types of data sets. First is simulated ones, where 1000 random samples are generated for 3 different distributions each (Uniform, Normal and Laplace) for each of the sample sizes 2, 5, 10, 30, 100 and 500. That is 1000 × 3 × 6 sample sets. These samples are generated with NumPy's random Generator, seeded so that every run gives the same numbers. The second is a real data set: Global YouTube Statistics 2023 from Kaggle. 5,000 samples are taken of sizes 10, 30, 100, 300 and 900, with and without replacement. Then, sample means are calculated and plotted to check the underlying distribution of sample means, against the normal distribution the central limit theorem predicts.

Distributions

Distributions considered here are of continuous random variable. The probability density functions of these distributions are given below:

1. Uniform Distribution

If the probability distribution of a random variable X follows the below function, then it is called Uniform distribution.

$$f(x) = \begin{cases} \frac{1}{b-a} & a \leq x \leq b \\ 0 & otherwise \end{cases}$$

$f(x)$ is the probability density function of the uniform distribution.

$a$ and $b$ are the lower and upper limits of the distribution.

PDF of Uniform distribution is defined over a closed interval $[a, b]$. the PDF is constant within this interval and zero outside of it.

2. Normal Distribution

If the probability distribution of a random variable follows the below probability density function, then the distribution is called Normal or Gaussian distribution.

$$f(x) = \frac{1}{\sigma \sqrt{2\pi}} e^{-\frac{(x-\mu)^2}{2\sigma^2}}$$

$f(x)$ is the probability density function of the normal distribution.

$\mu$ is the mean of the distribution, it represents the location of the peak of the bell curve.

$\sigma$ is the standard deviation of the distribution, it represents the width/spread of the bell curve.

This formula describes how the probability density varies for different values of x in a normal distribution. The normal distribution is symmetric and bell-shaped, and it is often used to model various natural phenomena and statistical processes due to its mathematical properties and prevalence in real-world data.

3. Laplace Distribution

If the probability distribution of a random variable follows the below probability density function, then the distribution is called Laplace distribution.

$$f(x) = \frac{1}{2b} e^{-\frac{|x-\mu|}{b}}$$

$f(x)$ is the probability density function of the Laplace distribution.

$\mu$ is the mean of the distribution, it represents the location of the peak.

$b$ is the scale parameter of the distribution, it represents the spread. The variance is $2b^2$.

The absolute value of x−μ in the exponent ensures that the Laplace distribution is symmetric about its mean μ. It is characterised by a sharp peak at μ and heavy tails. The Laplace distribution is often used in statistics and data analysis, particularly in situations where data is sparse or exhibits sudden changes or outliers.

Samples

All the samples come from one seeded generator, rng = np.random.default_rng(42). For each population and each sample size $n$, a single call draws a $1000 \times n$ array, and each of its rows is one sample of size $n$.

Population NumPy call What the parameters mean Mean Variance
Uniform rng.uniform(low=-5, high=15, size=(1000, n)) low and high are the ends of the interval: every value is at least low and less than high 5 $20^2/12 \approx 33.3$
Normal rng.normal(loc=5, scale=2, size=(1000, n)) loc is the mean $\mu$ and scale the standard deviation $\sigma$ 5 $2^2 = 4$
Laplace rng.laplace(loc=5, scale=2, size=(1000, n)) loc is $\mu$, the position of the peak, and scale is $b$ in the density above (so the rate of the exponential decay is $1/b$) 5 $2b^2 = 8$

The sample sizes are $n$ = 2, 5, 10, 30, 100 and 500.

Results

import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.io as pio
from plotly.subplots import make_subplots
from scipy import stats

pio.renderers.default = "plotly_mimetype+notebook_connected"
rng = np.random.default_rng(42)

def sample_means(draw, n, reps=1000):
    """Draw reps samples of size n at once, as a (reps, n) array, and average each row."""
    return draw((reps, n)).mean(axis=1)

pops = {
    "Uniform(-5, 15)": lambda size: rng.uniform(-5, 15, size),
    "Normal(5, 2)":    lambda size: rng.normal(5, 2, size),
    "Laplace(5, 2)":   lambda size: rng.laplace(5, 2, size),
}
# The population mean and standard deviation, from the formulas in the table above.
moments = {
    "Uniform(-5, 15)": (5, 20 / np.sqrt(12)),
    "Normal(5, 2)":    (5, 2),
    "Laplace(5, 2)":   (5, 2 * np.sqrt(2)),
}
sizes = (2, 5, 10, 30, 100, 500)

means = {name: {n: sample_means(draw, n) for n in sizes} for name, draw in pops.items()}

The three functions below draw every figure and table in the results: a histogram of the sample means for each $n$ with the normal density $N(\mu, \sigma^2/n)$ on top, a QQ-plot of the standardised means $\sqrt{n}\,(\bar{X}_n - \mu)/\sigma$ against $N(0, 1)$, and a table of the mean, standard deviation, skewness and excess kurtosis of the means. For a normal distribution the skewness and the excess kurtosis are both 0. With 1,000 means, chance alone moves the skewness by about $\pm 0.15$ and the excess kurtosis by about $\pm 0.3$ (twice their standard errors, $\sqrt{6/1000}$ and $\sqrt{24/1000}$), so values inside those bands are indistinguishable from normal. The last column is the Kolmogorov-Smirnov distance, the largest gap between the CDF of the standardised means and $\Phi$; for 1,000 draws from an exact normal it is below $1.36/\sqrt{1000} \approx 0.043$ in 95% of runs.

Show code
BLUE, ORANGE, GREY = "#5C86B0", "#C75716", "#8A93A6"   # the same colour for the same thing in every panel

def short(values, digits=4):
    """Floats to a few significant figures, as a plain list: finer than a chart can show,
    and a fraction of the page weight of full-precision numbers."""
    return [float(f"{v:.{digits}g}") for v in np.asarray(values, dtype=float)]

def plot_sampling(samples, mu, spread, unit="sample mean", bins=30, cols=2):
    """One panel per n: a density histogram of the sample means, with the normal density
    N(mu, spread(n)^2) that the central limit theorem predicts drawn on top. The bars are
    binned here, so the page carries 30 or 40 bars per panel rather than every mean."""
    ns = list(samples)
    rows = -(-len(ns) // cols)
    fig = make_subplots(rows=rows, cols=cols, subplot_titles=[f"n = {n}" for n in ns],
                        horizontal_spacing=0.12, vertical_spacing=0.32 / rows)
    for i, n in enumerate(ns):
        row, col = i // cols + 1, i % cols + 1
        density, edges = np.histogram(samples[n], bins=bins, density=True)
        sd = spread(n)
        grid = np.linspace(min(edges[0], mu - 4 * sd), max(edges[-1], mu + 4 * sd), 101)
        fig.add_bar(x=short((edges[:-1] + edges[1:]) / 2, 7), y=short(density),
                    width=float(edges[1] - edges[0]), marker_color=BLUE, opacity=0.65,
                    name="sample means", legendgroup="means", showlegend=i == 0, row=row, col=col)
        fig.add_scatter(x=short(grid, 6), y=short(stats.norm.pdf(grid, mu, sd)), mode="lines",
                        line=dict(color=ORANGE, width=2), name="normal density from the CLT",
                        legendgroup="normal", showlegend=i == 0, row=row, col=col)
        if row == rows:
            fig.update_xaxes(title_text=unit, row=row, col=col)
        if col == 1:
            fig.update_yaxes(title_text="density", row=row, col=col)
    fig.update_layout(bargap=0, height=230 * rows + 150)
    fig.show()

def thin(count):
    """Which of the sorted points a QQ-plot draws: the most extreme 1% at each end, where
    the tails show, and 200 evenly spaced between them, where thousands of points
    would only overlap into a line."""
    ends = max(10, count // 100)
    inner = np.linspace(ends, count - ends - 1, 200).round().astype(int)
    return np.unique(np.r_[np.arange(ends), inner, np.arange(count - ends, count)])

def qq_plot(series, ns=(10, 100)):
    """QQ-plots of the standardised sample means against N(0, 1), one panel per n.
    `series` maps a legend name to (samples, mu, spread, colour)."""
    fig = make_subplots(rows=1, cols=len(ns), subplot_titles=[f"n = {n}" for n in ns],
                        shared_yaxes=True, horizontal_spacing=0.06)
    for j, n in enumerate(ns, start=1):
        for name, (samples, mu, spread, colour) in series.items():
            z = (samples[n] - mu) / spread(n)
            (theoretical, ordered), _ = stats.probplot(z)
            keep = thin(len(z))
            fig.add_scatter(x=short(theoretical[keep]), y=short(ordered[keep]), mode="markers",
                            marker=dict(color=colour, size=5, opacity=0.75), name=name,
                            legendgroup=name, showlegend=j == 1, row=1, col=j)
        fig.add_scatter(x=[-4, 4], y=[-4, 4], mode="lines", line=dict(color=GREY, dash="dash"),
                        name="N(0, 1): the line y = x", legendgroup="line", showlegend=j == 1,
                        row=1, col=j)
        fig.update_xaxes(title_text="N(0, 1) quantile", tickvals=[-2, 0, 2], row=1, col=j)
    fig.update_yaxes(title_text="standardised sample mean", row=1, col=1)
    fig.update_layout(height=440)
    fig.show()

def summary(samples, mu, spread, theory="σ/√n", digits=3):
    """The moments of the sample means for each n, next to what the theory predicts."""
    rows = []
    for n, m in samples.items():
        z = (m - mu) / spread(n)
        rows.append({
            "n": n,
            "mean of the means": m.mean(),
            "sd of the means": m.std(ddof=1),
            theory: spread(n),
            "skewness": stats.skew(m),
            "excess kurtosis": stats.kurtosis(m),
            "KS distance": stats.kstest(z, "norm").statistic,
        })
    return pd.DataFrame(rows).set_index("n").map(f"{{:.{digits}f}}".format)

1. Uniform Distribution

Test

name = "Uniform(-5, 15)"
mu, sigma = moments[name]
spread = lambda n: sigma / np.sqrt(n)      # the standard deviation of the mean, sigma / sqrt(n)
plot_sampling(means[name], mu, spread)
Means of samples from Uniform(-5, 15), with the normal density N(5, 33.3/n) that the central limit theorem predicts. Each panel has its own x scale.
qq_plot({"Uniform(-5, 15)": (means[name], mu, spread, BLUE)})
QQ-plots of the standardised means from Uniform(-5, 15) against N(0, 1).
summary(means[name], mu, spread)
mean of the means sd of the means σ/√n skewness excess kurtosis KS distance
n
2 5.057 4.190 4.082 -0.035 -0.608 0.034
5 4.835 2.596 2.582 0.062 -0.170 0.044
10 5.048 1.765 1.826 0.030 -0.044 0.024
30 5.042 1.017 1.054 0.054 0.220 0.038
100 4.996 0.581 0.577 0.076 0.102 0.028
500 4.993 0.254 0.258 0.098 0.053 0.027

Comments

  1. Sample means are highly dispersed for smaller sample sizes as possible values of random variables have equal probability.

  2. With the increase in sample size, variance decreases, as $\sigma^2/n$: the standard deviation of the means goes from 4.19 at n = 2 (theory $5.77/\sqrt{2} = 4.08$) to 0.254 at n = 500 (theory 0.258).

  3. At n = 2 the mean of two uniform values has a triangular distribution, with lighter tails than the normal curve (excess kurtosis −0.61, where the theory gives $-1.2/n = -0.6$). By n = 10 the histogram follows the normal curve, the QQ-plot points lie on the line, and the skewness and excess kurtosis are inside the bands that chance alone produces.

2. Normal Distribution

Test

name = "Normal(5, 2)"
mu, sigma = moments[name]
spread = lambda n: sigma / np.sqrt(n)
plot_sampling(means[name], mu, spread)
Means of samples from Normal(5, 2), with the normal density N(5, 4/n). Each panel has its own x scale.
qq_plot({"Normal(5, 2)": (means[name], mu, spread, BLUE)})
QQ-plots of the standardised means from Normal(5, 2) against N(0, 1).
summary(means[name], mu, spread)
mean of the means sd of the means σ/√n skewness excess kurtosis KS distance
n
2 4.956 1.466 1.414 -0.116 -0.113 0.032
5 4.939 0.893 0.894 0.104 -0.070 0.042
10 4.997 0.633 0.632 0.012 0.028 0.019
30 5.009 0.353 0.365 0.130 0.399 0.028
100 5.008 0.193 0.200 0.100 0.197 0.040
500 5.006 0.088 0.089 0.029 -0.021 0.037

Comments

  1. The sample means are normally distributed for all sample sizes. Here this is exact, not an approximation: a sum of independent normal variables is itself normal.
  2. The distribution becomes skinnier and symmetric about the mean with the increase in sample size: the standard deviation of the means goes from 1.47 at n = 2 (theory $2/\sqrt{2} = 1.41$) to 0.088 at n = 500 (theory 0.089).
  3. Confidence intervals shrink shorter.
  4. Since these means are exactly normal, their table shows what chance alone does with 1,000 means: a skewness of up to 0.13, and an excess kurtosis of 0.40 at n = 30, a little outside the $\pm 0.3$ band. Across the 18 rows of the three tables, one or two values outside the bands are to be expected.

3. Laplace Distribution

Test

name = "Laplace(5, 2)"
mu, sigma = moments[name]
spread = lambda n: sigma / np.sqrt(n)
plot_sampling(means[name], mu, spread)
Means of samples from Laplace(5, 2), with the normal density N(5, 8/n). Each panel has its own x scale.
qq_plot({"Laplace(5, 2)": (means[name], mu, spread, BLUE)})
QQ-plots of the standardised means from Laplace(5, 2) against N(0, 1).
summary(means[name], mu, spread)
mean of the means sd of the means σ/√n skewness excess kurtosis KS distance
n
2 5.023 1.989 2.000 -0.016 1.649 0.039
5 5.004 1.245 1.265 0.126 0.579 0.032
10 4.979 0.895 0.894 0.103 0.190 0.029
30 5.006 0.510 0.516 -0.013 0.194 0.019
100 5.005 0.273 0.283 0.005 -0.195 0.024
500 5.000 0.123 0.126 0.013 -0.062 0.026

Comments

  1. The sample means are very close to normal from about n = 10. At n = 2 they have a sharper peak and heavier tails than the normal curve (excess kurtosis 1.65, where the theory gives $3/n = 1.5$, since the Laplace distribution itself has excess kurtosis 3), and at n = 5 the excess kurtosis is still 0.58. By n = 10 it is 0.19, inside the band that chance alone produces, and the QQ-plot points lie on the line.
  2. The variance of the sample mean decreases with the increase in sample size, as $8/n$: the standard deviation of the means goes from 1.99 at n = 2 (theory 2.00) to 0.123 at n = 500 (theory 0.126).

Real Data Set

Global YouTube dataset: Source

The Kaggle page gives the dataset's licence as "Other (specified in description)", and the description does not specify one, so for licence reasons the data file is not included in this site's repository. The cell below downloads it from Kaggle the first time it runs. No Kaggle sign-in is needed: Kaggle serves public datasets without an account. The cell saves the file as CentralLimitTheorem/_YouTube_Statistics.csv, beside the notebook, where git ignores it, and later runs read that copy.

import io
import urllib.request
import zipfile
from pathlib import Path

# The leading underscore keeps the local copy from being published with the post.
# The path is relative to the notebook's own folder, blogs/; it also works when run
# from the repository root or from blogs/CentralLimitTheorem/.
if Path.cwd().name == "CentralLimitTheorem":
    data_dir = Path(".")
elif Path("blogs/CentralLimitTheorem.ipynb").exists():     # the repository root
    data_dir = Path("blogs/CentralLimitTheorem")
else:                                                     # blogs/, the notebook's folder
    data_dir = Path("CentralLimitTheorem")
data_path = data_dir / "_YouTube_Statistics.csv"
if not data_path.exists():
    url = "https://www.kaggle.com/api/v1/datasets/download/nelgiriyewithana/global-youtube-statistics-2023"
    with urllib.request.urlopen(url, timeout=60) as response:
        archive = zipfile.ZipFile(io.BytesIO(response.read()))
    data_dir.mkdir(exist_ok=True)
    data_path.write_bytes(archive.read("Global YouTube Statistics.csv"))

df = pd.read_csv(data_path, encoding="latin-1")      # Kaggle's file is Latin-1, not UTF-8
df[["rank", "Youtuber", "subscribers", "category", "Country"]].head()
rank Youtuber subscribers category Country
0 1 T-Series 245000000 Music India
1 2 YouTube Movies 170000000 Film & Animation United States
2 3 MrBeast 166000000 Entertainment United States
3 4 Cocomelon - Nursery Rhymes 162000000 Education United States
4 5 SET India 159000000 Shows India
subscribers = df["subscribers"].to_numpy() / 1e6      # in millions
N = len(subscribers)
mu = subscribers.mean()
sigma = subscribers.std()              # divisor N: the 995 channels are the whole population here
skew_pop = stats.skew(subscribers)
print(f"{N} channels, {df['subscribers'].isna().sum()} missing subscriber counts, "
      f"{(df['video views'] == 0).sum()} channels with 0 video views")
print(f"subscribers: mean {mu:.2f} million, standard deviation {sigma:.2f} million, "
      f"skewness {skew_pop:.2f}, excess kurtosis {stats.kurtosis(subscribers):.1f}")
995 channels, 0 missing subscriber counts, 8 channels with 0 video views
subscribers: mean 22.98 million, standard deviation 17.52 million, skewness 5.51, excess kurtosis 45.5

The subscriber counts run from 12.3 million to 245 million, with a median of 17.7 million. Here the 995 channels are the whole population that we sample from, so $\mu$ and $\sigma$ are computed from all of them, with divisor $N$. A skewness of 5.51 and an excess kurtosis of 45.5 mean a long right tail: a few channels have ten times the typical count. Eight channels list 0 video views, which cannot be right for channels with over 12 million subscribers, but only the subscribers column is used here, and it has no missing values.

Population Distribution

counts, edges = np.histogram(subscribers, bins=np.arange(12, 247))     # bins one million wide
fig = go.Figure(go.Bar(x=short((edges[:-1] + edges[1:]) / 2), y=counts.tolist(), width=1,
                       marker_color=BLUE, name="channels"))
fig.add_vline(x=mu, line=dict(color=ORANGE, dash="dash"),
              annotation_text=f"mean {mu:.2f} million", annotation_position="top right")
fig.update_layout(xaxis_title="subscribers (millions)", yaxis_title="number of channels", bargap=0)
fig.show()
Distribution of subscribers over the 995 channels (mean 22.98 million).

From this population we draw 5,000 samples of each size, with and without replacement, using the same sample_means function as for the simulations. With replacement the draws are independent, and the standard deviation of the mean is $\sigma/\sqrt{n}$. Without replacement it is smaller by the finite-population correction:

$$\operatorname{sd}(\bar{X}_n) = \frac{\sigma}{\sqrt{n}} \sqrt{\frac{N - n}{N - 1}},$$

so the normal curve drawn over those histograms uses this standard deviation.

reps = 5000
real_sizes = (10, 30, 100, 300, 900)
schemes = {
    "with replacement": lambda size: rng.choice(subscribers, size, replace=True),
    # Each row is the whole population in a fresh random order; its first n entries are
    # a sample of size n drawn without replacement.
    "without replacement": lambda size: rng.permuted(np.tile(subscribers, (size[0], 1)), axis=1)[:, :size[1]],
}
real_means = {scheme: {n: sample_means(draw, n, reps) for n in real_sizes}
              for scheme, draw in schemes.items()}

def fpc(n):
    """The finite-population correction: how much smaller the standard deviation of the
    mean is without replacement than with it."""
    return np.sqrt((N - n) / (N - 1))

spreads = {
    "with replacement": lambda n: sigma / np.sqrt(n),
    "without replacement": lambda n: sigma / np.sqrt(n) * fpc(n),
}
hist_sizes = (10, 30, 100, 300)
plot_sampling({n: real_means["with replacement"][n] for n in hist_sizes}, mu, spreads["with replacement"],
              unit="sample mean (millions)", bins=40)
Means of samples drawn with replacement, with the normal density N(μ, σ²/n). Each panel has its own x scale.
plot_sampling({n: real_means["without replacement"][n] for n in hist_sizes}, mu, spreads["without replacement"],
              unit="sample mean (millions)", bins=40)
Means of samples drawn without replacement, with the normal density whose standard deviation includes the finite-population correction. Each panel has its own x scale.
qq_plot({scheme: (real_means[scheme], mu, spreads[scheme], colour)
         for scheme, colour in (("with replacement", BLUE), ("without replacement", ORANGE))})
QQ-plots of the standardised means of subscriber counts against N(0, 1).
pd.concat({scheme: summary(real_means[scheme], mu, spreads[scheme], theory="theory sd")
           for scheme in schemes}, names=["sampling"])
mean of the means sd of the means theory sd skewness excess kurtosis KS distance
sampling n
with replacement 10 22.980 5.618 5.539 1.954 6.510 0.121
30 22.932 3.156 3.198 1.037 1.867 0.079
100 22.965 1.752 1.752 0.591 0.525 0.048
300 23.006 0.994 1.011 0.285 0.192 0.017
900 22.989 0.592 0.584 0.149 0.099 0.010
without replacement 10 23.145 5.635 5.514 1.670 3.719 0.108
30 22.968 3.146 3.151 1.016 1.568 0.073
100 22.967 1.667 1.662 0.517 0.218 0.048
300 22.981 0.849 0.846 0.162 -0.127 0.025
900 22.983 0.182 0.181 -0.491 0.213 0.037

Neither scheme gives normal means at n = 30 or n = 100. Both histograms have a long right tail that the normal curve misses, and in the QQ-plots the largest means lie well above the line; the excess kurtosis (1.9 and 1.6 at n = 30) and the Kolmogorov-Smirnov distance (0.048 at n = 100 for both, where 5,000 normal draws would stay below $1.36/\sqrt{5000} \approx 0.019$) say the same. The standard deviation of the means, on the other hand, matches the theory to within about 2% in every row, and the mean of the means matches $\mu$ to within the simulation noise.

The skewness shows how slowly the shape becomes normal. The skewness of a mean of $n$ independent draws is the population skewness divided by $\sqrt{n}$, so with $\gamma = 5.51$ it is about 1.0 at n = 30 and 0.55 at n = 100, and only at n ≈ 3,000 would it reach 0.1. Without replacement the third moment of the mean has a finite-population factor of its own, and the skewness becomes

$$\gamma \, \frac{N - 2n}{N - 2} \sqrt{\frac{N - 1}{n\,(N - n)}},$$

which is 0.46 at n = 100: a little smaller, and still clearly skewed. It changes sign at $n = N/2$, because the mean of a large sample is decided by the few channels left out of it. A sample of 900 is the population minus 95 channels, so its mean is the mirror image of the mean of those 95, which is skewed to the right.

def skew_with(n):
    return skew_pop / np.sqrt(n)

def skew_without(n):
    # the same, times the finite-population factor for the third moment of the mean
    return skew_pop / np.sqrt(n) * (N - 2 * n) / (N - 2) * np.sqrt((N - 1) / (N - n))

curve = np.geomspace(10, 900, 80)
fig = go.Figure()
for scheme, colour, theory in (("with replacement", BLUE, skew_with), ("without replacement", ORANGE, skew_without)):
    fig.add_scatter(x=short(curve), y=short(theory(curve)), mode="lines", line=dict(color=colour, dash="dash"),
                    name=f"theory, {scheme}")
    fig.add_scatter(x=list(real_sizes), y=short([stats.skew(real_means[scheme][n]) for n in real_sizes]),
                    mode="markers", marker=dict(color=colour, size=9), name=f"simulation, {scheme}")
fig.add_hline(y=0, line=dict(color=GREY, width=1))
fig.update_xaxes(type="log", tickvals=list(real_sizes), title_text="sample size n (log scale)")
fig.update_layout(yaxis_title="skewness")
fig.show()
Skewness of the sample mean against n: the simulation (dots) and the theory (dashed).

The spread is where the two schemes differ. The table below divides the standard deviation of the means without replacement by the one with replacement, and puts the ratio next to the finite-population correction $\sqrt{(N - n)/(N - 1)}$:

sd_with = np.array([real_means["with replacement"][n].std(ddof=1) for n in real_sizes])
sd_without = np.array([real_means["without replacement"][n].std(ddof=1) for n in real_sizes])
pd.DataFrame({
    "ratio": sd_without / sd_with,
    "√((N − n)/(N − 1))": fpc(np.array(real_sizes)),
    "sd with replacement": sd_with,
    "sd without replacement": sd_without,
}, index=pd.Index(real_sizes, name="n")).map("{:.3f}".format)
ratio √((N − n)/(N − 1)) sd with replacement sd without replacement
n
10 1.003 0.995 5.618 5.635
30 0.997 0.985 3.156 3.146
100 0.952 0.949 1.752 1.667
300 0.854 0.836 0.994 0.849
900 0.307 0.309 0.592 0.182

The ratio agrees with the correction to within the simulation noise, about 2% here. Up to n = 100 the correction is at most 5%, too little to change the shape of the distribution; at n = 900, nine tenths of the population, the means without replacement are about three times less spread out, because every sample is almost the whole population.

fig = go.Figure()
for scheme, colour in (("with replacement", BLUE), ("without replacement", ORANGE)):
    fig.add_bar(x=[str(n) for n in real_sizes], y=short([real_means[scheme][n].mean() for n in real_sizes]),
                name=f"mean of the means, {scheme}", marker_color=colour)
fig.add_hline(y=mu, line=dict(color=GREY, dash="dash"), annotation_text=f"true mean {mu:.2f} million",
              annotation_position="top left")
fig.update_xaxes(type="category")
fig.update_layout(barmode="group", xaxis_title="Sample Size", yaxis_title="Mean of Sample Means (millions)")
fig.show()
Means for different sample sizes.

Where the Central Limit Theorem Fails

The Cauchy distribution

Every result above rests on one assumption of the theorem: the population has a finite variance $\sigma^2$. The standard Cauchy distribution, with density

$$f(x) = \frac{1}{\pi\,(1 + x^2)},$$

looks like a bell curve with fatter tails, but its tails are so heavy that it has no variance, and not even a mean: $E|X| = \infty$. Its characteristic function is $E\,e^{itX} = e^{-|t|}$, so the mean of $n$ independent draws has the characteristic function $\big(e^{-|t|/n}\big)^n = e^{-|t|}$, the same as one draw. The mean of 1,000 Cauchy draws is exactly as spread out as a single draw: averaging gains nothing, and no amount of data makes $\bar{X}_n$ settle down.

To see it, we follow the running mean $\bar{X}_n$ as the draws come in, up to 100,000 draws, three times for the standard normal and three times for the standard Cauchy (rng.standard_cauchy). Both are centred at 0, and the figure draws 200 points of each run on a log scale rather than all 100,000.

extra_rng = np.random.default_rng(42)      # a fresh seeded generator for the sections below
n_max, runs = 100_000, 3
steps = np.unique(np.geomspace(1, n_max, 200).round().astype(int))
draws = {"standard normal": extra_rng.standard_normal, "standard Cauchy": extra_rng.standard_cauchy}
RUN_COLOURS = (BLUE, ORANGE, "#5E9C6B")

fig = make_subplots(rows=1, cols=2, subplot_titles=list(draws), shared_yaxes=True, horizontal_spacing=0.06)
paths = {}
for j, (name, draw) in enumerate(draws.items(), start=1):
    running = np.cumsum(draw((runs, n_max)), axis=1) / np.arange(1, n_max + 1)
    paths[name] = running
    for k, colour in enumerate(RUN_COLOURS):
        fig.add_scatter(x=steps.tolist(), y=short(running[k, steps - 1]), mode="lines",
                        line=dict(color=colour, width=1.5), name=f"run {k + 1}",
                        legendgroup=f"run {k + 1}", showlegend=j == 1, row=1, col=j)
    fig.add_hline(y=0, line=dict(color=GREY, width=1, dash="dash"), row=1, col=j)
    fig.update_xaxes(type="log", title_text="number of draws n (log scale)", row=1, col=j)
fig.update_yaxes(title_text="running mean", row=1, col=1)
fig.update_layout(height=440)
fig.show()
Running mean of up to 100,000 draws, three seeded runs each: standard normal (left) and standard Cauchy (right). The panels share the y scale; the x axis is logarithmic.
checkpoints = [10, 100, 1_000, 10_000, 100_000]
pd.DataFrame({(name, f"run {k + 1}"): running[k, np.array(checkpoints) - 1]
              for name, running in paths.items() for k in range(runs)},
             index=pd.Index(checkpoints, name="n")).map("{:.3f}".format)
standard normal standard Cauchy
run 1 run 2 run 3 run 1 run 2 run 3
n
10 -0.336 0.130 -0.167 -0.298 -2.598 -1.377
100 -0.050 -0.120 -0.020 -0.479 -0.303 -0.339
1000 -0.029 -0.005 -0.029 3.042 14.129 -0.060
10000 -0.010 -0.006 -0.004 2.173 -0.410 -1.884
100000 -0.004 0.003 0.002 0.031 2.156 -1.350

The table puts numbers on "the same distribution as one draw". For each population it draws 5,000 samples of size $n$ and gives the quartiles of their means, next to the upper quartile the theory predicts: $0.674/\sqrt{n}$ for the normal, and 1 for the Cauchy whatever $n$ is.

rows = {}
for name, draw in draws.items():
    for n in (1, 10, 1000):
        m = draw((5000, n)).mean(axis=1)
        theory = stats.norm.ppf(0.75) / np.sqrt(n) if name == "standard normal" else stats.cauchy.ppf(0.75)
        rows[(name, n)] = [*np.quantile(m, [0.25, 0.5, 0.75]), theory]
pd.DataFrame(rows, index=["lower quartile", "median", "upper quartile", "theory, upper quartile"]).T \
  .rename_axis(["population", "n"]).map("{:.3f}".format)
lower quartile median upper quartile theory, upper quartile
population n
standard normal 1 -0.687 -0.022 0.668 0.674
10 -0.203 0.004 0.227 0.213
1000 -0.020 0.002 0.022 0.021
standard Cauchy 1 -0.991 0.028 0.975 1.000
10 -0.944 0.031 1.051 1.000
1000 -1.011 0.005 1.033 1.000
  1. The normal running means settle on 0: at n = 1,000 all three are within 0.03 of it, and at n = 100,000 within 0.004, as a standard deviation of $1/\sqrt{n}$ predicts. The Cauchy running means never settle. Every so often one draw is so large that it outweighs all the draws before it, the running mean jumps, and then it drifts back only slowly as later draws dilute that one value. Run 2 is at −0.30 after 100 draws, 14.13 after 1,000, −0.41 after 10,000 and 2.16 after 100,000; two of the three runs are further from 0 after 100,000 draws than after 100.
  2. The quartiles of the Cauchy means stay near −1 and 1 at n = 1, 10 and 1,000, as the theory says, while those of the normal means shrink like $0.674/\sqrt{n}$, to ±0.02 at n = 1,000. The mean of 1,000 Cauchy draws is no better an estimate of the centre than a single draw. The sample median would do far better here, because it ignores how far out the extreme values are.

Very heavy tails

The Cauchy is the extreme case, but the theorem also fails, more quietly, for any population with a finite mean and an infinite variance. A Pareto distribution with tail index $\alpha$ has $P(X > x) \propto x^{-\alpha}$ for large $x$, and for $1 < \alpha < 2$ its mean exists but its variance does not. The law of large numbers still holds, so $\bar{X}_n \to \mu$, but more slowly than $1/\sqrt{n}$: the error shrinks like $n^{1/\alpha - 1}$, which is $n^{-1/3}$ for $\alpha = 1.5$, and the rescaled mean converges to a stable distribution that is skewed to the right, not to a normal one (the generalised central limit theorem). For $\alpha \le 1$ there is no mean at all, and the running mean of these positive values grows without bound. Any finite list of numbers, such as the 995 subscriber counts, has a finite variance, so the theorem does apply to sampling from it; but when the data look like a sample from a power law, the variance is dominated by a few of the largest values, and $\sigma/\sqrt{n}$ estimated from a sample can be badly wrong.

How Large Does n Need to Be?

The Berry–Esseen bound

The central limit theorem says that $P(Z_n \le z) \to \Phi(z)$, but not how fast. The Berry–Esseen theorem answers that when the population also has a finite third absolute moment $\rho = E|X - \mu|^3$: for IID draws and every $n$,

$$\sup_z \big| P(Z_n \le z) - \Phi(z) \big| \le \frac{C\,\rho}{\sigma^3 \sqrt{n}},$$

where $C$ is a constant that does not depend on the population; the best value proved so far is $C \le 0.4748$, and no value below 0.4097 can work. So the largest error in any probability computed from the normal approximation shrinks like $1/\sqrt{n}$, and the ratio $\rho/\sigma^3$, which is never smaller than the absolute skewness, sets how large it is to begin with. A population whose ratio is four times larger needs sixteen times the sample size for the same guarantee. The bound is a worst case over every population with that ratio, so it is loose: it is not zero even for the Normal population, whose means are exactly normal. The table gives the ratio for the four populations in this post, the bound with $C = 0.4748$, and the Kolmogorov-Smirnov distance measured above at n = 100 (with replacement for the subscriber counts, since the theorem is about independent draws), which estimates the left-hand side.

ratio = {   # rho / sigma^3: from the population formulas, and from the 995 channels for YouTube
    "Uniform(-5, 15)": 3 * np.sqrt(3) / 4,
    "Normal(5, 2)": 2 * np.sqrt(2 / np.pi),
    "Laplace(5, 2)": 6 / 2 ** 1.5,
    "YouTube subscribers": np.mean(np.abs(subscribers - mu) ** 3) / sigma ** 3,
}
ks_100 = {name: stats.kstest((means[name][100] - m) / (s / np.sqrt(100)), "norm").statistic
          for name, (m, s) in moments.items()}
ks_100["YouTube subscribers"] = stats.kstest(
    (real_means["with replacement"][100] - mu) / spreads["with replacement"](100), "norm").statistic
C = 0.4748
pd.DataFrame({
    "skewness": [0, 0, 0, skew_pop],
    "ρ/σ³": ratio.values(),
    "bound at n = 30": [C * r / np.sqrt(30) for r in ratio.values()],
    "bound at n = 100": [C * r / np.sqrt(100) for r in ratio.values()],
    "KS distance at n = 100": ks_100.values(),
}, index=pd.Index(ratio, name="population")).map("{:.3f}".format)
skewness ρ/σ³ bound at n = 30 bound at n = 100 KS distance at n = 100
population
Uniform(-5, 15) 0.000 1.299 0.113 0.062 0.028
Normal(5, 2) 0.000 1.596 0.138 0.076 0.040
Laplace(5, 2) 0.000 2.121 0.184 0.101 0.024
YouTube subscribers 5.505 5.630 0.488 0.267 0.048

Every measured distance is below its bound, and well below it: for the subscriber counts the bound at n = 100 is 0.267 and the measured distance 0.048. (The distances for the simulations are close to the 0.027 that 1,000 draws from an exact normal give on average, about $0.87/\sqrt{1000}$, so they mostly measure the noise of the experiment.) What the bound gets right is the order of things. The three symmetric populations have ratios between 1.30 and 2.12, and the subscriber counts 5.63, so by the bound the subscriber counts need between 7 and 19 times the sample size for the same accuracy, and for every population halving the bound takes four times as many draws.

When is n = 30 enough?

The rule of thumb that n = 30 is enough works for populations like the first three here: symmetric, with light tails. For them it is generous, since the Uniform and Laplace means were already very close to normal at n = 10. Skewness is what breaks the rule, because the skewness of the mean is $\gamma/\sqrt{n}$. Cochran's rule of thumb for survey sampling asks for $n > 25\,\gamma^2$ before trusting a 95% interval from the normal approximation, which keeps the skewness of the mean below 0.2; for the subscriber counts that is $25 \times 5.51^2 \approx 760$ channels, most of the population of 995. And with an infinite variance, as for the Cauchy, no $n$ is enough.

The bootstrap is the usual alternative when the normal approximation is in doubt. Instead of assuming a normal shape, it resamples the one sample we have, with replacement, many times, and treats the spread of the resampled means as the sampling distribution; the 2.5% and 97.5% quantiles of those means are the percentile interval. It needs no formula for the standard error, so it works for a median or a ratio as easily as for a mean. But it is not a cure for small samples from a skewed population, because it can only see the part of the tail that made it into the sample. The cell below draws 2,000 samples of each size from the subscriber counts, with replacement, and counts how often a nominal 95% interval contains the true mean, for the usual $t$ interval, $\bar{x} \pm t_{0.975,\,n-1}\, s/\sqrt{n}$, and for the bootstrap percentile interval from 2,000 resamples.

reps_ci, B = 2000, 2000
rows = []
for n in (10, 30, 100, 300):
    samples = extra_rng.choice(subscribers, (reps_ci, n))
    m, s = samples.mean(axis=1), samples.std(axis=1, ddof=1)
    covered_t = np.abs(m - mu) <= stats.t.ppf(0.975, n - 1) * s / np.sqrt(n)
    covered_boot = np.empty(reps_ci, dtype=bool)
    for i, sample in enumerate(samples):
        boot_means = extra_rng.choice(sample, (B, n)).mean(axis=1)
        low, high = np.quantile(boot_means, [0.025, 0.975])
        covered_boot[i] = low <= mu <= high
    too_low = m + stats.t.ppf(0.975, n - 1) * s / np.sqrt(n) < mu       # t intervals entirely below mu
    rows.append({"n": n, "t interval": covered_t.mean(), "bootstrap percentile interval": covered_boot.mean(),
                 "t interval misses that lie below μ": too_low.mean() / (1 - covered_t.mean())})
pd.DataFrame(rows).set_index("n").map("{:.1%}".format)
t interval bootstrap percentile interval t interval misses that lie below μ
n
10 81.8% 78.0% 99.4%
30 85.2% 85.2% 99.3%
100 89.6% 89.8% 97.1%
300 92.3% 92.3% 94.8%

Both intervals fall short of 95% at every n here, and by about the same amount: 81.8% and 78.0% at n = 10, 85.2% for both at n = 30, and still only 92.3% at n = 300. (With 2,000 samples, each percentage is uncertain by about ±1.5 points.) Almost all the misses are on one side: about 95% to 99% of the $t$ intervals that miss lie entirely below $\mu$. A small sample often contains none of the few huge channels, so its mean is too low and its spread too small, and resampling that sample cannot bring the missing channels back. The bootstrap earns its place when there is no formula for the standard error, as for a median, or as a check on the normal approximation. Refinements such as the BCa interval adjust for skewness, but they too can only work with the part of the tail that the sample shows; for the mean of strongly skewed data, the real remedy is a larger sample.

Conclusions:

Simulated Data

  1. The distribution of sample means is close to Normal for large sample sizes, irrespective of the original population distribution, and the histograms with the normal density drawn on top, the QQ-plots and the tables show it rather than leaving it to the eye. For the Normal population it holds exactly at every sample size. For the Uniform and Laplace populations it is an approximation that is visibly off at n = 2 (excess kurtosis −0.61 and 1.65) and already very good at n = 10, where the skewness and excess kurtosis of the means are inside the bands that chance alone produces and the QQ-plot points lie on the line.

  2. For each distribution, the variance of sample means is inversely proportional to the sample size: in every row of the three tables the standard deviation of the means is within 4% of $\sigma/\sqrt{n}$, which is less than twice the standard error of a standard deviation estimated from 1,000 values (about 2.2%). The larger the sample size, the smaller the variance of sample means distribution. The confidence in estimating the population mean increases with the increase in sample size, which coincides with the central limit theorem.

  3. For each distribution, the mean of the sample means is equal to the mean of the original population, 5, to within the simulation noise: every value in the tables is between 4.84 and 5.06, within about two standard errors (the standard deviation of the means divided by $\sqrt{1000}$).

  4. Comparing three different distributions, the sample means of uniform distribution is more spread out than the other two distributions. At the same time, the sample means of samples from a normal distribution is the most compact of the three. This is because the variance of uniform distribution (33.3) is higher than those of the Laplace (8) and normal (4) distributions.

Real Dataset

  1. The original population distribution is skewed to the right, with a skewness of 5.51, and for such a population normality emerges slowly. The skewness of the sample mean falls only like $5.51/\sqrt{n}$: about 1.0 at n = 30 and 0.55 at n = 100 (the simulation gives 1.04 and 0.59 with replacement). So at n = 100 the sample means are still visibly right-skewed, with or without replacement, and the rule of thumb that n = 30 is enough does not hold for data like this.

  2. Difference between sampling with replacement and without replacement: sampling without replacement mainly reduces the spread of the sample means, by the finite-population correction $\sqrt{(N-n)/(N-1)}$. For N = 995 that is 0.985 at n = 30 and 0.949 at n = 100, so up to n = 100 the two sampling distributions differ by at most 5% in spread and very little in shape (skewness 0.59 and 0.52 at n = 100). The correction only matters when the sample is a sizeable fraction of the population: at n = 900 the means without replacement are about three times less spread out (ratio 0.31), and their skewness even turns negative.

Takeaways

  • The mean of the sample means is $\mu$ and their standard deviation is $\sigma/\sqrt{n}$ for any population with a finite variance; what depends on the population is how soon their shape is normal (and without a finite variance, as for the Cauchy distribution, averaging may gain nothing at all). For the Uniform and Laplace populations it is very close by n = 10, and for a Normal population it is exact at every n. Check it with a normal density drawn over the histogram, a QQ-plot and the skewness and kurtosis of the means, not by eye alone.
  • Skewness is what slows the central limit theorem down. The skewness of a mean of $n$ draws is the population's skewness divided by $\sqrt{n}$, so for YouTube subscriber counts (skewness 5.5) the means are still visibly skewed at n = 100, and n = 30 is far from enough: at n = 30 a nominal 95% interval covers the true mean only 85% of the time, whether it comes from the $t$ formula or the bootstrap. Look at the skewness of the data before trusting a normal approximation; Cochran's rule $n > 25\gamma^2$ asks for about 760 here.
  • Sampling without replacement from a population of $N$ shrinks the standard deviation of the mean by $\sqrt{(N - n)/(N - 1)}$: 5% at n = 100 out of 995, which leaves the shape as it was. It only matters when the sample is a sizeable fraction of the population.

References

  1. G. Casella and R. L. Berger, Statistical Inference, 2nd edition, Duxbury, 2002. Section 5.5 covers convergence in distribution and the central limit theorem.
  2. L. Wasserman, All of Statistics, Springer, 2004. Chapter 5, "Convergence of Random Variables".
  3. W. G. Cochran, Sampling Techniques, 3rd edition, Wiley, 1977. Chapter 2 derives the finite-population correction for sampling without replacement, and gives the rule of thumb $n > 25\,G_1^2$ for the normal approximation.
  4. N. Elgiriyewithana, Global YouTube Statistics 2023, Kaggle, 2023.
  5. NumPy documentation: Random Generator, with uniform, normal, laplace, standard_cauchy, choice and permuted.
  6. SciPy documentation: scipy.stats.probplot and scipy.stats.kstest.
  7. W. Feller, An Introduction to Probability Theory and Its Applications, Volume II, 2nd edition, Wiley, 1971. Covers the Berry–Esseen theorem, and the stable laws that take the place of the normal one when the variance is infinite.
  8. I. G. Shevtsova, On the absolute constants in the Berry–Esseen type inequalities for identically distributed summands, arXiv:1111.6554, 2011. The source of the constant 0.4748.
  9. B. Efron and R. J. Tibshirani, An Introduction to the Bootstrap, Chapman & Hall, 1993. The percentile and BCa intervals.