10 Sampling, statistics and simulation
A probability model describes a population of possible observations. Statistics begins when the model is an incomplete description and we must learn from a realized sample. We distinguish the observed numbers \(x_1,\ldots,x_n\) from the random variables \(X_1,\ldots,X_n\) that would be observed under repeated sampling. A statistic is a function of the sample, not a function of unknown parameters.
10.1 Summaries of a sample
For a numerical sample, useful summaries include
\[ \bar x=\frac1n\sum_i x_i,\qquad s^2=\frac1{n-1}\sum_i(x_i-\bar x)^2. \]
The mean minimizes the sum of squared deviations from a constant: for any \(a\),
\[ \sum_i(x_i-a)^2=\sum_i(x_i-\bar x)^2+n(\bar x-a)^2, \]
because the cross term contains \(\sum_i(x_i-\bar x)=0\). The median minimizes the sum of absolute deviations: away from the observed points, the slope of \(\sum_i|x_i-a|\) equals the number of observations below \(a\) minus the number above it. A minimum therefore occurs where at least half of the points lie on each side.
Quantiles report position rather than magnitude. The empirical CDF
\[ \widehat F_n(x)=\frac1n\sum_{i=1}^n\mathbf1_{\{X_i\le x\}} \]
is a random step function that estimates the population CDF \(F\). Its value at a fixed \(x\) is unbiased for \(F(x)\) and has variance \(F(x)(1-F(x))/n\) under iid sampling. The LLN establishes pointwise consistency at any fixed \(x\). The interquartile range is the 75th percentile minus the 25th percentile and provides a measure of spread less sensitive to outliers than standard deviation.
10.1.1 Why the variance uses n minus one
Assume iid observations with mean \(\mu\) and variance \(\sigma^2\). The sample variance is
\[ S^2=\frac{\sum_i(X_i-\bar X)^2}{n-1}. \]
Using the previous identity at \(a=\mu\),
\[ \sum_i(X_i-\bar X)^2=\sum_i(X_i-\mu)^2-n(\bar X-\mu)^2. \]
Taking expectations gives \(n\sigma^2-n(\sigma^2/n)=(n-1)\sigma^2\). Thus \(E[S^2]=\sigma^2\) when \(n\ge2\). Dividing by \(n\) instead produces a downward-biased variance estimator, though it remains consistent.
The standard deviation \(S\) is not generally exactly unbiased for \(\sigma\), even though \(S^2\) is unbiased for \(\sigma^2\). A nonlinear transformation need not preserve unbiasedness.
10.2 Sampling distributions and standard errors
The sampling distribution of a statistic is the distribution that would result if we repeated the data collection procedure at the same sample size. Its standard deviation is the statistic’s standard error. For the sample mean under iid sampling,
\[ \operatorname{SE}(\bar X)=\frac{\sigma}{\sqrt n}. \]
This differs from \(\sigma\), which measures the spread of individual observations. When \(\sigma\) is unknown, we estimate the standard error using \(S/\sqrt n\).
For iid \(X_i\sim N(\mu,\sigma^2)\), normal closure under sums shows \(\bar X\sim N(\mu,\sigma^2/n)\) exactly. Moreover, a remarkable independence property holds for normal samples.
10.2.1 Exact normal-sample theory
Let \(Z=(X-\mu\mathbf1)/\sigma\) be the standardized \(n\)-dimensional sample vector, with independent standard normal components. Choose an orthogonal matrix \(Q\) whose first row is \(\mathbf1^\top/\sqrt n\). This is possible by extending that unit vector to an orthonormal basis. Then \(W=QZ\) has independent standard normal entries: its joint density is unchanged because \(\|QZ\|=\|Z\|\) and \(|\det Q|=1\).
The first entry is \(W_1=\sqrt n(\bar X-\mu)/\sigma\). The remaining coordinates are orthogonal to \(\mathbf1\). Preservation of squared lengths gives
\[ \sum_{j=2}^n W_j^2=\frac{1}{\sigma^2}\sum_{i=1}^n(X_i-\bar X)^2 =\frac{(n-1)S^2}{\sigma^2}. \]
By Chapter 7 and Chapter 8, a sum of \(k\) independent squared standard normals is \(\chi_k^2=\operatorname{Gamma}(k/2,1/2)\). Consequently,
\[ \boxed{\frac{(n-1)S^2}{\sigma^2}\sim\chi^2_{n-1}}, \qquad \bar X\ \perp\ S^2. \]
The independence follows because \(W_1\) is independent of all remaining \(W_j\). The dimension \(n-1\) is the number of independent orthogonal residual directions. These are exact results for normal samples; mean and variance are not generally independent in nonnormal samples.
10.3 Student’s t distribution
If \(Z\sim N(0,1)\) and \(V\sim\chi_\nu^2\) are independent, their ratio
\[ T=\frac{Z}{\sqrt{V/\nu}} \]
has Student’s \(t_\nu\) distribution. The density follows by conditioning on \(V=v\) and changing variables \(z=t\sqrt{v/\nu}\):
\[ \begin{aligned} f_T(t)&=\int_0^\infty\phi(t\sqrt{v/\nu})\sqrt{v/\nu}\,f_V(v)\,dv\\ &=\frac{\Gamma((\nu+1)/2)} {\sqrt{\nu\pi}\,\Gamma(\nu/2)} \left(1+\frac{t^2}{\nu}\right)^{-(\nu+1)/2}. \end{aligned} \]
The second line evaluates a gamma integral with rate \((1+t^2/\nu)/2\). Compared to a normal density, a small-degree-of-freedom t density has heavier tails because a small random denominator can produce an unusually large ratio. As \(\nu\to\infty\), \(V/\nu\to1\) in probability by the LLN and the t law converges to \(N(0,1)\).
For normal data, put the previous exact normal-sample results into the ratio to obtain the pivot
\[ \frac{\bar X-\mu}{S/\sqrt n}\sim t_{n-1}. \]
This result is the basis of exact normal-model confidence intervals and t-tests.
10.4 Monte Carlo estimation
Many integrals can be interpreted as expectations. For any integrable \(g(X)\),
\[ I=E[g(X)]\approx\widehat I_N=\frac1N\sum_{j=1}^N g(X_j). \]
When the simulated \(X_j\) are iid and \(\operatorname{Var}(g(X))<\infty\), the estimate is unbiased and has standard error \(\sqrt{\operatorname{Var}(g(X))/N}\). The CLT suggests a numerical error interval \(\widehat I_N\pm1.96\,s_g/\sqrt N\) for large \(N\). This describes randomness in the simulation estimate; it is not uncertainty about whether the underlying mathematical model is appropriate.
10.4.1 Example: integrate a smooth function
For \(I=\int_0^1e^{-x^2}\,dx\), set \(U\sim\operatorname{Uniform}(0,1)\). Then \(I=E[e^{-U^2}]\). We can compare numerical quadrature with Monte Carlo:
import numpy as np
from scipy.integrate import quad
rng = np.random.default_rng(1010)
u = rng.random(100_000)
y = np.exp(-u**2)
estimate = y.mean()
se = y.std(ddof=1)/np.sqrt(y.size)
exact, quad_error = quad(lambda x: np.exp(-x*x), 0, 1)
print("Monte Carlo:", estimate, "+/-", 1.96*se)
print("Quadrature:", exact)Quadrature is excellent for this one-dimensional smooth integrand. Monte Carlo becomes valuable when expectations are multidimensional or the random variable is easier to simulate than integrate.
10.5 Rejection sampling
Suppose we need draws from a density \(f\) but can only sample from an easier density \(q\). Find a finite \(M\ge1\) such that \(f(x)\le Mq(x)\) everywhere (ignoring null sets). Independently propose \(X\sim q\) and \(U\sim\operatorname{Uniform}(0,1)\); accept \(X\) if \(U\le f(X)/(Mq(X))\).
For any set \(A\),
\[ P(X\in A,\text{accept})=\int_A q(x)\frac{f(x)}{Mq(x)}\,dx =\frac1M\int_A f(x)\,dx. \]
Taking \(A\) to be the whole support gives \(P(\text{accept})=1/M\). Conditioning on acceptance recovers \(f\). Independent proposals yield independent accepted values. The efficiency is governed by \(1/M\), not merely by the convenience of sampling \(q\).
For \(f(x)=6x(1-x)\) on \((0,1)\), choose uniform proposals \(q(x)=1\) and \(M=1.5\). The acceptance probability conditional on a proposal is \(4x(1-x)\).
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
rng = np.random.default_rng(1011)
x, u = rng.random((2, 40_000))
accepted = x[u<=4*x*(1-x)]
print("Acceptance rate:", accepted.size/x.size, "Theory:", 2/3)
g = np.linspace(0, 1, 201)
plt.hist(accepted, bins=45, density=True, alpha=.5)
plt.plot(g, stats.beta.pdf(g, 2, 2))
plt.xlabel("Accepted value")
plt.ylabel("Density")
plt.show()10.6 Practice problems
Work in your browser with Google Colab, or download the notebooks for Jupyter.
Practice notebook
Worked solutions
10.6.1 Exercise 1: Distinguish two sources of variation
Suppose measurements have mean 14 and standard deviation six. Find the standard deviation of a single observation and the standard error of the mean of 36 independent observations. How many observations reduce the standard error to 0.5?
The single-observation standard deviation is six. The mean’s standard error is \(6/\sqrt{36}=1\). To achieve \(6/\sqrt n\le0.5\), require \(n\ge144\). Four times as many observations halve the standard error.
10.6.2 Exercise 2: Bias of a naive variance estimator
Let \(\widehat V=n^{-1}\sum_i(X_i-\bar X)^2\) for an iid sample with variance \(\sigma^2\). Derive its bias.
The residual-sum-of-squares identity gives \(E[\sum_i(X_i-\bar X)^2]=(n-1)\sigma^2\). Therefore \(E[\widehat V]=(1-1/n)\sigma^2\) and the bias is \(-\sigma^2/n\).
10.6.3 Exercise 3: An exact pivot
For a sample of eight iid \(N(\mu,4)\) variables, identify the law of \(7S^2/4\), then express \(P(S^2>6)\) as a chi-square tail probability. Is \(S^2\) independent of \(\bar X\)?
\(7S^2/4\sim\chi^2_7\). Thus \(P(S^2>6)=P(\chi^2_7>10.5)\). The sample mean and variance are independent by the orthogonal decomposition proof.
10.6.4 Exercise 4: Replicate normal sampling (Python)
Generate 30,000 samples of size six from \(N(10,9)\). Compare the standardized sample means, scaled sample variances, and studentized means to the three exact reference distributions. Estimate correlation between the first two.
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
rng = np.random.default_rng(1001)
n = 6
x = rng.normal(10, 3, (30_000, n))
m, s = x.mean(axis=1), x.std(axis=1, ddof=1)
z = (m-10)*np.sqrt(n)/3
v = (n-1)*s**2/9
t = (m-10)*np.sqrt(n)/s
fig, axes = plt.subplots(1, 3, figsize=(10, 3))
for ax, values, law, bounds in zip(
axes, [z,v,t], [stats.norm(),stats.chi2(5),stats.t(5)],
[(-4,4),(0,25),(-6,6)]
):
g = np.linspace(*bounds, 300)
ax.hist(values, bins=65, density=True, alpha=.5)
ax.plot(g, law.pdf(g))
ax.set(xlim=bounds)
print("Correlation:", np.corrcoef(z,v)[0,1])
plt.tight_layout()
plt.show()
assert abs(np.corrcoef(z,v)[0,1]) < .03The studentized mean has heavier tails than the standardized mean with known \(\sigma\). The sample correlation should be near zero; exact independence follows from the model proof.
10.6.5 Exercise 5: Monte Carlo integration with uncertainty (Python)
Estimate \(\int_0^2\cos(x^2)\,dx\) from 100,000 uniform proposals. Report a large-sample 95% numerical error interval and compare with quadrature. How must the integrand be scaled?
Under \(U\sim\operatorname{Uniform}(0,2)\), \(E[2\cos(U^2)]\) equals the integral.
import numpy as np
from scipy.integrate import quad
rng = np.random.default_rng(1002)
x = rng.uniform(0, 2, 100_000)
g = 2*np.cos(x*x)
se = g.std(ddof=1)/np.sqrt(g.size)
value, _ = quad(lambda x: np.cos(x*x), 0, 2)
print("estimate:", g.mean())
print("95% numerical interval:", g.mean()+np.array([-1,1])*1.96*se)
print("quadrature:", value)
assert abs(g.mean()-value) < 5*seThe factor two converts the uniform-density-weighted integral into the ordinary unweighted integral on an interval of length two.
10.6.6 Exercise 6: Construct a rejection sampler (Python)
The target density is \(f(x)=3x^2\) on \(0<x<1\). Use uniform proposals and find the smallest possible \(M\). Generate 60,000 proposals and check the accepted values against the true mean and CDF.
\(M=3\) bounds the ratio \(f/q\). Accept with probability \(x^2\), giving overall acceptance rate \(1/3\). The CDF is \(x^3\); the mean is \(3/4\).
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(1003)
x, u = rng.random((2, 60_000))
y = np.sort(x[u<x*x])
print("Acceptance:", y.size/x.size, "mean:", y.mean())
plt.step(y, np.arange(1, y.size+1)/y.size, label="Empirical CDF")
g = np.linspace(0,1,200)
plt.plot(g, g**3, "--", label="Theory")
plt.legend()
plt.show()
assert abs(y.mean()-.75) < .01Because accepted values have density proportional to \(q(x)x^2=x^2\), normalization by the acceptance probability produces exactly \(3x^2\).