Track: core · Prerequisites: Chapters 1, 3 and 4
Reading: Taylor, ch. 5, 10 and 11 · Bevington & Robinson, ch. 2 · Fornasini, ch. 5 and 6 · Rouaud, ch. I and III
Part I treated an uncertainty as a standard deviation and combined standard deviations in quadrature, without saying much about the distributions behind them. This part of the book supplies the missing probability and statistics. This chapter introduces the distributions that occur most often in measurement, and explains why one of them, the normal distribution, appears almost everywhere.
A random variable is described by its distribution; its mean and variance are the two numbers error analysis uses most.
The binomial, Poisson and normal distributions are related as limits of one another.
The uniform, exponential and Cauchy distributions each describe a common situation, and the Cauchy distribution is a warning.
The central limit theorem explains why sums and means of many independent contributions are normally distributed, and how fast.
The sample statistics of Chapter 4 have their own distributions: , Student’s and .
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
try:
import errprop as ep
except ImportError: # running from a clone without `pip install -e .`
import sys
sys.path.insert(0, "../..")
import errprop as ep
ep.use_style()
rng = np.random.default_rng(105)5.1 Random variables and their distributions¶
A measured value that changes unpredictably from one repetition to the next is a random variable. For a discrete variable (a count) the distribution is a set of probabilities with ; for a continuous variable it is a probability density , with and .
Two numbers summarise a distribution. The mean (expectation value)
locates it, and the variance
measures its width. Why the variance, rather than, say, the mean absolute deviation? Because variances of independent quantities add. For independent and ,
since . No other measure of width combines this simply, and this one property is the root of quadrature addition (Section 1.4) and of the whole of Chapter 3.
Higher moments describe the shape: the skewness measures asymmetry, the excess kurtosis measures how heavy the tails are compared with a normal distribution, for which both are zero.
5.2 Binomial, Poisson and normal¶
Binomial. An experiment is repeated times; each trial succeeds with probability , independently of the others. The number of successes has the binomial distribution
The variance follows from the additivity above: is a sum of independent trials, each 1 with probability and 0 otherwise, so each has variance . A typical use is an efficiency: if a detector records of particles, the efficiency has standard uncertainty , which is small both when the efficiency is close to 0 and when it is close to 1.
Poisson. If is very large and very small, with fixed, the binomial distribution becomes
This is the distribution of the number of independent rare events in a fixed interval: radioactive decays, photons, cosmic rays, molecules crossing a surface. That the variance equals the mean is the origin of the rule of counting experiments (Chapter 6).
Normal. For large the Poisson distribution, and for large the binomial, approach the normal (Gaussian) distribution
for which the probability of lying within , and of the mean is 68.27 %, 95.45 % and 99.73 %.
for k_sigma in (1, 2, 3):
print(f"P(|x - mu| < {k_sigma} sigma) = {stats.norm.cdf(k_sigma) - stats.norm.cdf(-k_sigma):.4f}")
# binomial with fixed n p = 4 approaching Poisson; Poisson approaching normal
k = np.arange(0, 15)
for n in (8, 40, 400):
d = np.abs(stats.binom.pmf(k, n, 4 / n) - stats.poisson.pmf(k, 4)).max()
print(f"binomial(n={n:3d}, p={4 / n:.3f}) vs Poisson(4): largest difference in P(k) = {d:.4f}")
for mu in (4, 25, 100):
kk = np.arange(0, int(mu + 8 * np.sqrt(mu)))
d = np.abs(stats.poisson.pmf(kk, mu) - stats.norm.pdf(kk, mu, np.sqrt(mu))).max() / stats.poisson.pmf(int(mu), mu)
print(f"Poisson({mu:3d}) vs normal: largest difference relative to the peak = {d:.3f}")P(|x - mu| < 1 sigma) = 0.6827
P(|x - mu| < 2 sigma) = 0.9545
P(|x - mu| < 3 sigma) = 0.9973
binomial(n= 8, p=0.500) vs Poisson(4): largest difference in P(k) = 0.0781
binomial(n= 40, p=0.100) vs Poisson(4): largest difference in P(k) = 0.0105
binomial(n=400, p=0.010) vs Poisson(4): largest difference in P(k) = 0.0010
Poisson( 4) vs normal: largest difference relative to the peak = 0.131
Poisson( 25) vs normal: largest difference relative to the peak = 0.049
Poisson(100) vs normal: largest difference relative to the peak = 0.024
The Poisson distribution of mean 4 is visibly skewed (panel (a) of the figure below); at a mean of 25 the normal approximation is good to a few per cent of the peak height, which is why counts of more than about 20 are usually treated as normal.
5.3 Three more distributions¶
Uniform. on , with . It describes rounding by a digital display (Section 1.3), the phase of an unsynchronised oscillation, and any Type B statement “somewhere within ”. The sum of two independent uniform variables of equal width has a triangular distribution, for half-width .
Exponential. for , with mean and standard deviation both . It is the distribution of the waiting time between Poisson events and of the lifetime of an unstable particle or excited state. Its skewness is 2: the mean lies well above the median .
Cauchy (Lorentzian). , the shape of a resonance line, of the energy distribution of an unstable state, and of the ratio of two independent zero-mean normal variables. Its tails fall off so slowly () that the integrals for the mean and the variance do not converge. The distribution has a centre and a width , but no mean and no standard deviation. The consequence is striking: the average of Cauchy-distributed readings has the same distribution as a single reading, and averaging does not help at all (panel (d)). Error analysis built on standard deviations silently assumes distributions for which they exist, and a ratio with an uncertain denominator (Section 12.3) is where the assumption usually breaks.
for N in (1, 10, 1000):
means = rng.standard_cauchy((20_000, N)).mean(axis=1)
iqr = np.subtract(*np.quantile(means, [0.75, 0.25]))
print(f"Cauchy: interquartile range of the mean of {N:4d} readings = {iqr:.3f} (single reading: 2.000)")Cauchy: interquartile range of the mean of 1 readings = 2.019 (single reading: 2.000)
Cauchy: interquartile range of the mean of 10 readings = 2.001 (single reading: 2.000)
Cauchy: interquartile range of the mean of 1000 readings = 2.053 (single reading: 2.000)
5.4 The central limit theorem¶
Let be independent, with the same distribution of mean and finite variance . The central limit theorem states that the distribution of their mean approaches a normal distribution of mean and standard deviation as grows, whatever the original distribution. (Only the finite variance is required, which is exactly what the Cauchy distribution lacks.) The same holds for sums, and, with some conditions, for sums of variables with different distributions, provided no single term dominates.
This is why measurement errors are so often normal: an error is usually the sum of many small, independent disturbances (vibration, electrical noise, temperature fluctuations, reading), none of them dominant. It is also why the mean of a few readings is closer to normal than the readings themselves, which justifies the use of normal-theory intervals for means even when individual readings are not normal.
How fast does it happen? For a sum of independent terms, the skewness falls as and the excess kurtosis as . A symmetric distribution such as the uniform one converges very fast (the sum of three uniforms is already hard to distinguish from a normal distribution); a skewed one such as the exponential converges slowly.
print(" N skewness of the mean of N exponentials expected 2/sqrt(N)")
for N in (1, 2, 5, 10, 30, 100):
m = rng.exponential(1.0, (100_000, N)).mean(axis=1)
print(f"{N:3d} {stats.skew(m):.3f} {2 / np.sqrt(N):.3f}")
# how good is the normal 68 % interval for the mean of N exponential readings?
print("\n N P(|mean - mu| < sigma/sqrt(N))")
for N in (1, 3, 10, 30):
m = rng.exponential(1.0, (200_000, N)).mean(axis=1)
print(f"{N:3d} {np.mean(np.abs(m - 1) < 1 / np.sqrt(N)):.3f}") N skewness of the mean of N exponentials expected 2/sqrt(N)
1 2.021 2.000
2 1.398 1.414
5 0.907 0.894
10 0.638 0.632
30 0.365 0.365
100 0.205 0.200
N P(|mean - mu| < sigma/sqrt(N))
1 0.864
3 0.715
10 0.691
30 0.684
For a single exponential reading, covers 86 % instead of 68 %. For the mean of three readings the figure is already 72 %, and for ten readings 69 %: the width of the normal approximation becomes usable quickly, while the asymmetry of the distribution of the mean persists much longer (panel (c) of the figure below).
5.5 Distributions of sample statistics: , and ¶
Chapter 4 used three results without proof. They follow from three distributions, all derived from the normal one.
Chi-square. If are independent standard normal variables, has the distribution with degrees of freedom: mean , variance . For normal readings, has this distribution with ; the “lost” degree of freedom is the one used to compute . This is the source of the uncertainty of the standard deviation, (Section 4.3), and of the spread of a reduced chi-square (Section 11.4).
Student’s . has the distribution with degrees of freedom, whose heavier tails account for the uncertainty of (Section 4.4).
. The ratio of two independent reduced chi-squares, , compares two variances (Chapter 8).
A simulation confirms the first two for samples of five normal readings.
N, sigma = 5, 2.0
x = rng.normal(10.0, sigma, (200_000, N))
s = x.std(axis=1, ddof=1)
q = (N - 1) * s**2 / sigma**2
t = (x.mean(axis=1) - 10.0) / (s / np.sqrt(N))
print(f"(N-1) s^2 / sigma^2: mean {q.mean():.3f} (chi-square: {N - 1}), variance {q.var():.3f} (chi-square: {2 * (N - 1)})")
print(f"P(|t| < 1): simulated {np.mean(np.abs(t) < 1):.4f}, Student t(4) {stats.t.cdf(1, 4) - stats.t.cdf(-1, 4):.4f}, normal 0.6827")
print(f"mean of s = {s.mean():.3f} for sigma = {sigma}: s underestimates sigma on average by {1 - s.mean() / sigma:.1%}")(N-1) s^2 / sigma^2: mean 3.998 (chi-square: 4), variance 8.034 (chi-square: 8)
P(|t| < 1): simulated 0.6269, Student t(4) 0.6261, normal 0.6827
mean of s = 1.879 for sigma = 2.0: s underestimates sigma on average by 6.0%
The last line is worth noting: although is an unbiased estimate of , its square root is not an unbiased estimate of ; for five readings it is about 6 % low on average. Bias and other properties of estimators are the subject of Chapter 7.
fig, axes = plt.subplots(2, 2, figsize=(9.2, 7.2))
ax = axes[0, 0]
kk = np.arange(0, 41)
for mu, c in ((3, "C0"), (10, "C3"), (25, "C2")):
ax.plot(kk, stats.poisson.pmf(kk, mu), "o", ms=3.5, color=c, label=f"Poisson, $\\mu={mu}$")
xx = np.linspace(0, 40, 400)
ax.plot(xx, stats.norm.pdf(xx, mu, np.sqrt(mu)), "-", color=c, lw=1)
ax.set_xlabel("count $k$"); ax.set_ylabel("probability")
ax.legend(loc="upper right"); ep.panel_label(ax, "(a)", x=0.45)
ax = axes[0, 1]
xx = np.linspace(-5, 5, 801)
ax.plot(xx, stats.norm.pdf(xx), "k", lw=1.2, label="normal")
ax.plot(xx, stats.uniform.pdf(xx, -np.sqrt(3), 2 * np.sqrt(3)), "C0", label="uniform")
ax.plot(xx, stats.triang.pdf(xx, 0.5, -np.sqrt(6), 2 * np.sqrt(6)), "C2", label="triangular")
ax.plot(xx, stats.expon.pdf(xx + 1), "C1", label="exponential (shifted)")
ax.plot(xx, stats.cauchy.pdf(xx, 0, 0.6745), "C3", label="Cauchy")
ax.set_xlabel("$x$ (unit standard deviation; Cauchy: same quartiles)"); ax.set_ylabel("probability density")
ax.set_ylim(0, 0.62); ax.legend(loc="upper right", fontsize=8.5); ep.panel_label(ax, "(b)")
ax = axes[1, 0]
bins = np.linspace(-3, 4.5, 76)
for N, c in ((1, "C1"), (3, "C0"), (30, "C3")):
m = rng.exponential(1.0, (200_000, N)).mean(axis=1)
z = (m - 1) * np.sqrt(N)
ax.hist(z, bins=bins, density=True, histtype="step", lw=1.4, color=c, label=f"mean of {N}")
ax.plot(bins, stats.norm.pdf(bins), "k--", lw=1, label="normal")
ax.set_xlabel(r"$(\bar x - \mu)\sqrt{N}/\sigma$, exponential readings"); ax.set_ylabel("probability density")
ax.set_ylim(0, 1.0); ax.legend(loc="upper right"); ep.panel_label(ax, "(c)")
ax = axes[1, 1]
nn = np.arange(1, 10_001)
ax.plot(nn, np.cumsum(rng.normal(0, 1, nn.size)) / nn, "C0", lw=1, label="normal readings")
for i in range(3):
ax.plot(nn, np.cumsum(rng.standard_cauchy(nn.size)) / nn, color="C3", lw=0.9,
label="Cauchy readings" if i == 0 else None)
ax.axhline(0, color="k", lw=0.6)
ax.set_xscale("log"); ax.set_ylim(-6, 6)
ax.set_xlabel("number of readings $N$"); ax.set_ylabel("running mean")
ax.legend(loc="upper right"); ep.panel_label(ax, "(d)", y=0.12)
plt.show()
(a) Poisson distributions (points) and normal distributions of the same mean and variance (lines). (b) Five distributions scaled to unit standard deviation (the Cauchy distribution, which has none, is scaled to the same quartiles as the normal one). (c) The central limit theorem at work on exponential readings: the distribution of the mean approaches the normal one as grows, the skewness disappearing last. (d) Running means: for normal readings the mean settles as ; for Cauchy readings it never settles, and occasional huge readings throw it about at any .
Summary¶
Variances of independent quantities add; this single fact underlies quadrature and the propagation law.
Binomial Poisson for rare events, Poisson normal for large counts; the Poisson variance equals its mean.
The uniform distribution describes rounding and bounded Type B information, the exponential distribution waiting times and lifetimes.
The Cauchy distribution has no mean or variance; averaging does not reduce its spread. Ratios with uncertain denominators lead there.
By the central limit theorem, sums and means of many independent contributions with finite variance become normal, symmetric ones fast, skewed ones slowly.
The , and distributions describe sample variances and the statistics built from them.
Exercises¶
A detector registers 912 of 1000 incident particles. Give the efficiency with its binomial uncertainty. Why is the Poisson formula wrong here?
Show that the triangular distribution of half-width has standard deviation , and verify by summing two simulated uniform variables.
Simulate the ratio of two independent normal variables with means 0 and 1 and unit standard deviations. Compare its histogram with a Cauchy distribution. What changes when has mean 5?
Repeat the convergence study of Section 5.4 for the sum of values drawn from a distribution with skewness 6 (for example, a lognormal with ). How large must be for the skewness of the mean to fall below 0.2?
Using the distribution, find the exact 68 % interval for given from readings. Compare with .
Previous: 4. Repeated measurements · Next: 6. Counting statistics