Module contents
Lesson 2 of 27Review 80 min

Statistical models and sampling distributions

Establish the language of inference: a statistical model is a family of distributions indexed by a parameter, and a statistic is a sample function whose sampling distribution quantifies variation when the experiment is repeated. Construct sampling distributions by simulation and derive exact ones for normal samples (χ², Student’s t, and F), the basis of classical intervals and tests.

After this lesson you can

  • Formulate an applied problem as a parametric, semiparametric, or nonparametric statistical model and check parameter identifiability.
  • Simulate an arbitrary statistic’s sampling distribution and estimate its standard error with its own Monte Carlo error.
  • Derive χ², t, and F distributions from normals and prove independence of X̄ and S² in normal samples.
  • Explain why studentization changes the normal to a t distribution and when this matters in practice.

Before you start

Motivation: a number is not a conclusion

You train two variants of a model and evaluate them on the same validation set of n=400n = 400 examples. Variant A gets mean loss 2.312.31 and B gets 2.272.27. Is B better? Would A have won on another validation sample? The mean of 400400 numbers is a number, but one depending on which 400400 examples were drawn, and the question cannot be answered until we know how much it would have changed with another sample.

That is inferential statistics in a sentence: quantify the variability of what you calculate so you can distinguish information in the observations from sampling chance. The entire module (intervals, tests, bootstrap, Bayesian methods, linear models) rests on two objects fixed in this lesson:

  • a statistical model, stating which probability laws we consider possible for the data and which part of the law we want to know (the parameter);
  • the sampling distribution of a statistic, describing how the calculated number would be distributed if we repeated the experiment. From it comes the standard error, the error bar accompanying any serious figure.

A third, subtler thread: under normality, these sampling distributions can be calculated exactly for any nn, not just in the limit. They yield χ2\chi^2, Student’s tt, and FF, the basis of classical intervals and tests, all obtained from one geometric idea: an orthogonal rotation.

Four questions structure the lesson.

  1. What exactly is a model, and when is a parameter recoverable from data (identifiability)?
  2. What is a sampling distribution, and how can simulation obtain it for any statistic?
  3. What is the standard error, and what is it not (it is not the spread of the data)?
  4. What changes when σ\sigma is unknown and estimated from the same sample?

A note on prerequisites. We expect the descriptive statistics review (mean, sample variance, median) and probability from module 4: independence, change of variables for densities, multivariate Gaussian and its affine transformations. Data will always be X1,…,XnX_1, \dots, X_n independent and identically distributed (iid), Xˉ=1n∑iXi\bar X = \frac1n\sum_i X_i and S2=1n−1∑i(Xi−Xˉ)2S^2 = \frac{1}{n-1}\sum_i (X_i - \bar X)^2, unless otherwise stated.

Intuition: repeat the experiment

Before definitions, a thought experiment. A population (a probability law) supplies nn observations. From these nn observations calculate a number: a mean, maximum, or percentile. Record it, discard the sample, draw another, and repeat. The recorded numbers form a histogram, and this histogram, never actually seen in practice (there is only one sample), governs how much the observed number can be trusted.

InteractiveRepeat the experiment a thousand times
Replicate 300: 25 observations and their Xˉ\bar X
−0.03
  • Normal population
  • statistic for this sample
  • population value θ\theta
Sampling distribution of Xˉ\bar X after 300 replicates
  • histogram of replicates
  • theoretical N(θ,SE2)\Normal(\theta, \mathrm{SE}^2)
Simulated standard deviation of Xˉ\bar X versus nn (300 replicates per point), on a log-log scale
slope −1/2
  • simulation
  • this configuration
  • theoretical SE
  • slope −1/2 (reference)
25
Replicates BB300
Mean of Xˉ\bar X replicates−0.019
Population value θ\theta0.000
Simulated SE (± Monte Carlo error)0.196 ± 0.008
Theoretical SE0.200
Choose a population, statistic, and sample size nn, and press play. Each replicate draws a sample (top left, statistic in orange) and stacks its value in the histogram on the right, the sampling distribution. The dashed normal is N(θ,SE2)\Normal(\theta, \mathrm{SE}^2) with theoretical standard error when it exists. Below, simulated standard deviation of the statistic versus nn on log-log axes, with a reference line of slope −1/2-1/2. The question: what determines histogram width? Try the mean of a normal and increase nn; then the Pareto maximum; then the bimodal population median.

What you should have seen:

  • A normal mean narrows as 1/n1/\sqrt{n}. With n=25n = 25 the histogram centers near θ=0\theta = 0 with standard deviation 0.2=1/250.2 = 1/\sqrt{25}. On the lower graph points follow slope −1/2-1/2: whenever nn is multiplied by 100100, spread is divided by 1010. For n=5,20,100,500n = 5, 20, 100, 500 the graph (with 300300 replicates per point, or about 4 %4\,\% relative error) gives 0.44,0.24,0.11,0.0470.44, 0.24, 0.11, 0.047, while σ/n\sigma/\sqrt{n} gives 0.447,0.224,0.1,0.04470.447, 0.224, 0.1, 0.0447.
  • Each statistic has its own sampling distribution, and its width depends on the population. The normal median behaves like the mean, but 25 %25\,\% worse: its standard deviation is 1.25/n1.25/\sqrt{n} versus 1/n1/\sqrt{n}. For the exponential, mean and median tie. For a bimodal population (two separated peaks), the median is much worse than the mean: at n=500n = 500 median standard deviation is about 0.40.4 and mean standard deviation about 0.070.07, because the median lies in the valley between peaks, where data are scarce, and jumps from one to the other.
  • Some statistics’ variability does not decrease as 1/n1/\sqrt{n}. The maximum of a rate-11 exponential has variance exactly ∑k=1n1/k2\sum_{k=1}^{n} 1/k^2, increasing toward π2/6\pi^2/6: its standard deviation rises from 1.211.21 at n=5n = 5 to almost 1.281.28 (=π/6=\pi/\sqrt{6}, that of the Gumbel law) and stays there. The maximum grows (as ln⁡n\ln n), but does not concentrate. The normal maximum narrows, but exasperatingly slowly: its standard deviation falls from 0.670.67 at n=5n = 5 to 0.370.37 at n=500n = 500 (asymptotically, π/62ln⁡n\frac{\pi/\sqrt{6}}{\sqrt{2\ln n}}, giving 0.360.36 at n=500n = 500).
  • In some cases there is not even a width to measure. Pareto with α=1.5\alpha = 1.5 has finite mean and infinite variance. Simulated standard deviation of the mean does not stabilize (it jumps across nn and seeds): there is no standard error to report because the sample mean has no variance. The maximum is worse: its scale grows with nn, as n1/α=n2/3n^{1/\alpha} = n^{2/3}, and also has no finite variance, so its simulated standard deviation grows in jumps. The mean’s histogram nevertheless exists and is an asymmetric law with a long tail.
  • The 95th percentile and sample variance narrow with slope −1/2-1/2 (sample variance if the population has a finite fourth moment; percentile if density is positive at the quantile), but starting with greater spread. Sample-variance standard deviation for an exponential at n=20n = 20 is 0.640.64 (simulation gives 0.640.64 with 20002000 replicates), almost three times that of the mean (0.220.22): estimating variance is harder than estimating a mean.

The figure gives an operational lesson. A number calculated from a sample is one draw from the sampling distribution, whose width depends on three things: statistic, population, and nn. The rest of the lesson formalizes this idea (sections on models, sampling distributions, and standard error), learns to calculate widths by simulation and, for the normal case, exactly.

Statistical model: a family of possible laws

An observation is a realization of random variable XX whose law is unknown. A model explicitly states which laws are candidates. It is not a claim that nature is like this: it is the set of hypotheses among which data will choose.

Classification by the size of Θ\Theta organizes the module.

  • Parametric model: Θ⊆Rd\Theta \subseteq \R^d with finite dd. Examples: Bernoulli with Θ=(0,1)\Theta = (0, 1); normal N(μ,σ2)\Normal(\mu, \sigma^2) with Θ=R×(0,∞)\Theta = \R \times (0, \infty); exponential with rate λ∈(0,∞)\lambda \in (0, \infty); logistic regression P(Y=1∣x)=σ(w⊤x+b)\Pr(Y = 1 \given \vb{x}) = \sigma(\vb{w}\T\vb{x} + b) with θ=(w,b)\theta = (\vb{w}, b); a neural network with P(y∣x)=softmax⁡(fθ(x))\Pr(y \given \vb{x}) = \softmax(f_\theta(\vb{x})), where θ\theta comprises millions of weights. There is much to learn from few numbers.
  • Nonparametric model: Θ\Theta is infinite-dimensional. The basic example is P\mathcal{P} = all laws on R\R with finite second moment. Mean μ(P)=EP[X]\mu(P) = \E_P[X] is no longer a coordinate of θ\theta but a functional θ(P)\theta(P) of the law. Few assumptions are made at the cost of precision.
  • Semiparametric model: a finite-dimensional parameter of interest and an infinite-dimensional nuisance parameter. A typical example is Y=x⊤β+εY = \vb{x}\T\vb{\beta} + \varepsilon with E[ε∣x]=0\E[\varepsilon \given \vb{x}] = 0 and unspecified law of ε\varepsilon; β\vb{\beta} is of interest and the error law is nuisance. Another is Cox’s proportional hazards model, estimating effect β\vb{\beta} without modeling the baseline hazard function.

Fixing the model is the most important modeling decision because it determines which questions can be answered. Two nuances recur later. First, the parameter of interest may be only part or a function of θ\theta: for a normal, θ=(μ,σ2)\theta = (\mu, \sigma^2) but often only μ\mu matters (with σ2\sigma^2 as nuisance). Second, “well specified” is an idealization: “all models are wrong, but some are useful” (Box). What happens to an estimator when the true law is not in P\mathcal{P} is the subject of lesson 8 (sandwich variance, misspecified MLE).

A model is more than a family: it also fixes data structure. The iid assumption itself is part of the model and the first violated in practice (time series, repeated users, grouped data). The following sections assume iid; whenever they do, they use a model assumption, not a fact.

Identifiability: can data distinguish two parameters?

A parameter is useful if data can, at least in principle, distinguish it from another. If two different θ\theta values give exactly the same data law, no amount of data can decide between them.

The key phrase is “data law,” not “data.” This is not a small-data problem: it is a property of the parameterization and more samples do not fix it. Examples:

  • Redundant parameters. In y=a b x+εy = a\,b\,x + \varepsilon only product c=abc = ab matters. Pairs (a,b)(a, b) and (2a,b/2)(2a, b/2) give the same law, so (a,b)(a, b) is not identifiable; c=abc = ab is. This is the same phenomenon as ReLU-network scale symmetry: multiplying one layer by λ>0\lambda > 0 and the next by 1/λ1/\lambda leaves the function intact, so individual network weights have no separate “meaning.”
  • Mixtures with interchangeable labels. In π N(μ1,σ2)+(1−π) N(μ2,σ2)\pi\,\Normal(\mu_1, \sigma^2) + (1 - \pi)\,\Normal(\mu_2, \sigma^2), parameters (π,μ1,μ2)(\pi, \mu_1, \mu_2) and (1−π,μ2,μ1)(1 - \pi, \mu_2, \mu_1) give the same law (label switching). The parameterization is identifiable only up to permutation, fixed by imposing an order such as μ1<μ2\mu_1 < \mu_2.
  • Signs and scales. N(μ,σ2)\Normal(\mu, \sigma^2) parameterized by (μ,σ)(\mu, \sigma) with σ∈R\sigma \in \R is not identifiable: σ\sigma and −σ-\sigma yield the same law. With σ>0\sigma > 0 it is identifiable.
  • Collinearity. In y=Xβ+ε\vb{y} = \mat{X}\vb{\beta} + \vb{\varepsilon} with linearly dependent columns of X\mat{X}, β\vb{\beta} is not identifiable: β\vb{\beta} and β+v\vb{\beta} + \vb{v}, with Xv=0\mat{X}\vb{v} = \vb{0}, give the same mean. The combinations Xβ\mat{X}\vb{\beta} are identifiable, that is, estimable.
  • An identifiable case. An exponential with rate λ>0\lambda > 0: λ↦λe−λx\lambda \mapsto \lambda e^{-\lambda x} is injective, because E[X]=1/λ\E[X] = 1/\lambda recovers λ\lambda.

The important consequence is an impossibility result.

Proof

Since Pθ1=Pθ2P_{\theta_1} = P_{\theta_2}, also Pθ1⊗n=Pθ2⊗nP_{\theta_1}^{\otimes n} = P_{\theta_2}^{\otimes n}, and the law of Tn(X1,…,Xn)T_n(X_1, \dots, X_n) is the same under both parameters. If Tn→Pθ1T_n \xrightarrow{P} \theta_1 under θ1\theta_1, then P(∥Tn−θ1∥>ε)→0\Pr(\norm{T_n - \theta_1} > \eps) \to 0 for every ε>0\eps > 0, and that probability depends only on the law of TnT_n: the same holds under θ2\theta_2. If also Tn→Pθ2T_n \xrightarrow{P} \theta_2 under θ2\theta_2, the probability limit of TnT_n would be both θ1\theta_1 and θ2\theta_2, and probability limits are unique up to probability-zero sets: θ1=θ2\theta_1 = \theta_2, a contradiction.

∎

The next figure makes this visible with model y=a b x+εy = a\,b\,x + \varepsilon. The sum of squares SSE(a,b)=∑i(yi−ab xi)2\mathrm{SSE}(a, b) = \sum_i (y_i - ab\,x_i)^2 depends only on abab: it is SSE(a,b)=SSEmin⁡+Sxx (ab−c^)2\mathrm{SSE}(a, b) = \mathrm{SSE}_{\min} + S_{xx}\,(ab - \hat c)^2, with Sxx=∑ixi2S_{xx} = \sum_i x_i^2 and c^\hat c the least-squares estimate of cc.

InteractiveA nonidentifiable ridge
Sum of squares SSE(a,b)\mathrm{SSE}(a, b): bands of 11, 22 and 33 standard errors around the ridge
ab = ĉ
  • ridge ab=c^ab = \hat c (all with the same minimum SSE)
  • start (hollow) and end (filled) of each descent
Where each descent ends
starta finalb finalc = abSSE
(3.3, 1.2)3.0950.4451.37733.193
(1.4, 3.3)0.4583.0071.37733.193
(−3.0, −1.0)−2.863−0.4811.37733.193
(−1.2, −3.2)−0.460−2.9911.37733.193
(0.8, 0.6)1.2321.1181.37733.193
The optimizer returns a different pair (a,b)(a, b) on each run but always the same product. Columns aa and bb do not estimate anything: they depend on the starting point.
Model parameterization
1.5
0.80
Estimated product c^=a^b^\hat c = \hat a\hat b1.377
Standard error of c^\hat c0.129
SSE Hessian eigenvalues at optimum281.8 and 0
Last descent: aa, bb, abab1.23, 1.12, 1.377
Last descent: a2−b2a^2 - b^2 (invariant)0.267
On the (a,b)(a, b) plane, orange bands are points with ∣ab−c^∣≤j SE\abs{ab - \hat c} \le j\,\mathrm{SE} for j=1,2,3j = 1, 2, 3 (hyperbolas), and the thick line is the optimum ridge ab=c^ab = \hat c. Click the plane to launch gradient descent (hollow circle: start; filled: finish). What pair (a,b)(a, b) does the optimizer return, and what determines it? Click several places and compare the table. Then switch to 'Parameter c=abc = ab': the same sum of squares as a function of cc has one minimum and its standard error.

What you should have seen:

  • All descents end on the hyperbola, at different points. The table’s “c = ab” column is the same (to three decimals) in every row, as is final SSE: it is minimal. But “final a” and “final b” change between runs; what changes is the starting point, not data. There is not one minimum but a curve of minima.
  • The optimizer does not choose randomly: it preserves an invariant. The gradient flow of SSE\mathrm{SSE} preserves a2−b2a^2 - b^2, because a˙=−2Sxx(ab−c^) b\dot a = -2S_{xx}(ab - \hat c)\,b and b˙=−2Sxx(ab−c^) a\dot b = -2S_{xx}(ab - \hat c)\,a give  ⁣d ⁣dt(a2−b2)=2aa˙−2bb˙=0\frac{\dd}{\dd t}(a^2 - b^2) = 2a\dot a - 2b\dot b = 0. Small-step descent nearly preserves it (visible in the “a2−b2a^2 - b^2 (invariant)” readout, stable near its starting value). Thus initialization decided the reported pair. Publishing “a=2.1a = 2.1, b=0.7b = 0.7” publishes an artifact.
  • The Hessian exposes it. At the optimum, ∇2 SSE=2Sxx(b2ababa2)\hess\,\mathrm{SSE} = 2S_{xx}\begin{pmatrix} b^2 & ab \\ ab & a^2\end{pmatrix}, a rank-one matrix: eigenvalues 2Sxx(a2+b2)2S_{xx}(a^2 + b^2) and 00. The zero eigenvalue is the tangent direction to the ridge, where loss does not change. With parameter cc, the Hessian is scalar 2Sxx>02S_{xx} > 0: positive curvature, unique minimum, standard error σ^/Sxx\hat\sigma/\sqrt{S_{xx}} (the readout updates when noise σ\sigma or data change).
  • What to do. Switch to an identifiable parameterization (c=abc = ab), impose a constraint selecting one point (a=1a = 1, or ∣a∣=∣b∣\abs{a} = \abs{b} with a>0a > 0), or add information (a prior or penalty selecting within the ridge). What cannot be done is interpret aa and bb separately.

There is a local version of this idea, developed with Fisher information: a parameter is locally identifiable if the information matrix is regular. In the figure, the rank-one Hessian signals that it is not.

Statistics and sampling distributions

A statistic is a function of data that does not depend on the unknown parameter: T=T(X1,…,Xn)T = T(X_1, \dots, X_n) with measurable T:Xn→RkT : \mathcal{X}^n \to \R^k. Mean Xˉ\bar X, median, maximum, S2S^2, and a percentile are statistics. Difference Xˉ−μ\bar X - \mu is not, because μ\mu is unknown (it is called a pivotal quantity when its law does not depend on the parameter, the subject of lesson 9).

Since the data are random, TT is a random variable and its law depends on the true parameter.

It is a theoretical object: it describes what TT would do in infinitely many repetitions of the experiment, while in practice only one value is observed. There are only three ways to know it.

  1. Exactly, by calculation. Possible in few cases: the normal mean (with Xˉ∼N(μ,σ2/n)\bar X \sim \Normal(\mu, \sigma^2/n), immediate from affine transformations) and the normal theory below.
  2. Approximately, by asymptotic theory. By the central limit theorem, n(Xˉ−μ)/σ≈N(0,1)\sqrt{n}(\bar X - \mu)/\sigma \approx \Normal(0, 1) for large nn, for any finite-variance population. This is generalized (MLE, delta method) in lesson 8.
  3. By simulation, generating many samples from the model at a parameter value and calculating the statistic on each. This is what the figure above did, formalized in the simulation section.

The dependence on θ\theta deserves a warning: the sampling distribution is calculated assuming θ\theta is known (or using a candidate value), whereas in practice θ\theta is what we want to discover. All inference is an organized way around that circle: estimate missing θ\theta (plug-in), find a pivot independent of it (tt intervals), evaluate every candidate (tests), or replace the population law with the empirical one (bootstrap).

Standard error

Of the whole sampling distribution, width is most needed: it says how far the statistic would typically deviate from its central value on repetition of the experiment.

The fundamental case is the mean. If XiX_i are iid with mean μ\mu and variance σ2<∞\sigma^2 < \infty, the variance of a sum of independent variables gives

Var⁡(Xˉ)=1n2∑i=1nVar⁡(Xi)=σ2n,SE(Xˉ)=σn.\Var(\bar X) = \frac{1}{n^2}\sum_{i=1}^{n}\Var(X_i) = \frac{\sigma^2}{n}, \qquad \mathrm{SE}(\bar X) = \frac{\sigma}{\sqrt{n}}.

This is the figure’s −1/2-1/2 slope. Since σ\sigma is unknown, estimate it with SS and report SE^(Xˉ)=S/n\widehat{\mathrm{SE}}(\bar X) = S/\sqrt{n}. The justification is that S2/nS^2/n unbiasedly estimates Var⁡(Xˉ)=σ2/n\Var(\bar X) = \sigma^2/n. (Caution: SS is biased as an estimator of σ\sigma; by Jensen’s inequality, E[S]≤E[S2]=σ\E[S] \le \sqrt{\E[S^2]} = \sigma. Relative bias is order 1/n1/n and vanishes as nn grows, but “unbiased” describes S2S^2, not SS.)

Proof

With μ=E[X1]\mu = \E[X_1], ∑i(Xi−Xˉ)2=∑iXi2−nXˉ2\sum_i (X_i - \bar X)^2 = \sum_i X_i^2 - n\bar X^2. Since E[Xi2]=σ2+μ2\E[X_i^2] = \sigma^2 + \mu^2 and E[Xˉ2]=Var⁡(Xˉ)+μ2=σ2/n+μ2\E[\bar X^2] = \Var(\bar X) + \mu^2 = \sigma^2/n + \mu^2,

E[∑i(Xi−Xˉ)2]=n(σ2+μ2)−n(σ2n+μ2)=(n−1)σ2.\E\Big[\sum_i (X_i - \bar X)^2\Big] = n(\sigma^2 + \mu^2) - n\Big(\frac{\sigma^2}{n} + \mu^2\Big) = (n - 1)\sigma^2.

Dividing by n−1n - 1 gives E[S2]=σ2\E[S^2] = \sigma^2. (Dividing by nn would give n−1nσ2\frac{n-1}{n}\sigma^2: the sample mean fits data better than the true mean, so residuals underestimate spread.)

∎

Two common mistakes recur in the exercises. First, data standard deviation SS and standard error S/nS/\sqrt{n} are different things.

SS (sample standard deviation)SE^=S/n\widehat{\mathrm{SE}} = S/\sqrt{n} (standard error)
Measureshow much observations vary from each otherhow much the mean would vary across samples
As nn growsconverges to σ\sigma and stays thereshrinks as 1/n1/\sqrt{n}
Doubling nnunchanged (except noise)divided by 2≈1.41\sqrt{2} \approx 1.41
Used todescribe dataquantify estimator uncertainty

With n=400n = 400 observations and S=12S = 12 (for example, 400400 latencies in milliseconds), each observation deviates about 1212 ms from the mean, but the mean of 400400 is 12/400=0.612/\sqrt{400} = 0.6 ms from the true mean. To halve standard error requires four times more data, not twice as much.

Second, not all standard errors are σ/n\sigma/\sqrt{n}. Each statistic has its own. For the mean it is exact; for others it is known only asymptotically. The key example is the median.

Proof

Fix t∈Rt \in \R and let Nn=#{i:Xi≤m+t/n}N_n = \#\{i : X_i \le m + t/\sqrt{n}\}. Then X~n≤m+t/n\tilde X_n \le m + t/\sqrt{n} is equivalent to Nn≥n/2N_n \ge n/2 except on an event whose probability tends to zero (depending on how median is defined for even nn, the threshold is n/2n/2 or (n+1)/2(n+1)/2, and P(n/2≤Nn<n/2+1)→0\Pr(n/2 \le N_n < n/2 + 1) \to 0). Since Nn∼Bin(n,pn)N_n \sim \mathrm{Bin}(n, p_n) with pn=F(m+t/n)=12+f(m) t/n+o(n−1/2)p_n = F(m + t/\sqrt{n}) = \tfrac12 + f(m)\,t/\sqrt{n} + o(n^{-1/2}),

P(Nn≥n2)=P(Nn−npnnpn(1−pn)≥n/2−npnnpn(1−pn)).\Pr\Big(N_n \ge \frac{n}{2}\Big) = \Pr\Big(\frac{N_n - np_n}{\sqrt{np_n(1 - p_n)}} \ge \frac{n/2 - np_n}{\sqrt{np_n(1 - p_n)}}\Big).

The right side of the inner inequality converges to −2f(m) t-2f(m)\,t. The left side is a standardized sum of Bernoulli variables with parameter pn→1/2p_n \to 1/2 (a triangular array of bounded variables), converging to N(0,1)\Normal(0, 1) by Lindeberg-Feller. Thus P(n(X~n−m)≤t)→1−Φ(−2f(m) t)=Φ(2f(m) t)\Pr(\sqrt{n}(\tilde X_n - m) \le t) \to 1 - \Phi(-2f(m)\,t) = \Phi(2f(m)\,t), the distribution function of N(0,1/(4f(m)2))\Normal(0, 1/(4f(m)^2)).

∎

For a normal, f(0)=1/2πf(0) = 1/\sqrt{2\pi} and SE(X~)≈π/2/n=1.2533/n\mathrm{SE}(\tilde X) \approx \sqrt{\pi/2}/\sqrt{n} = 1.2533/\sqrt{n}: 25 %25\,\% more than the mean, as shown in the figure. For the bimodal, f(m)f(m) is tiny (the median is in the valley), asymptotic spread 1/(2f(m))1/(2f(m)) is enormous, and the formula describes median behavior only from a very large nn: at n=500n = 500 it predicts 17.1/500=0.7717.1/\sqrt{500} = 0.77 while simulation gives 0.420.42. A useful warning: do not blindly apply an asymptotic standard-error formula at moderate nn.

Simulation: the general recipe and its own precision

When no formula exists (a ratio of means, maximum, machine-learning statistic, evaluation metric), simulate. The recipe is always the same.

Recipe. Fix a parameter value θ\theta (or a law PP). For b=1,…,Bb = 1, \dots, B: generate X1(b),…,Xn(b)∼iidPθX^{(b)}_1, \dots, X^{(b)}_n \iid P_\theta and calculate T(b)=T(X1(b),…,Xn(b))T^{(b)} = T(X^{(b)}_1, \dots, X^{(b)}_n). The BB values T(1),…,T(B)T^{(1)}, \dots, T^{(B)} are an iid sample from the sampling distribution, and everything desired about it is estimated from them: mean, standard deviation (simulated standard error), and quantiles.

This is the figure above. A frequently forgotten point: simulation has its own error. With finite BB, simulated standard error s^=sd(T(1),…,T(B))\hat s = \mathrm{sd}(T^{(1)}, \dots, T^{(B)}) is another statistic with its own sampling distribution. Its precision can be quantified.

s^2=1B−1∑b=1B(T(b)−Tˉ)2\hat s^2 = \frac{1}{B - 1}\sum_{b=1}^{B}(T^{(b)} - \bar T)^2
The T(b)T^{(b)} are iid with variance τ2=SE2\tau^2 = \mathrm{SE}^2 (the estimated quantity) and kurtosis κ=E[(T−ET)4]/τ4\kappa = \E[(T - \E T)^4]/\tau^4.
1/4

Three practical consequences. (i) Simulated SE precision improves as 1/B1/\sqrt{B}: one more digit of precision requires 100100 times more replicates. (ii) The heavier the sampling-distribution tails (larger kurtosis κ\kappa), the worse the estimate. (iii) Every simulated figure needs its Monte Carlo error: error of a simulated mean is s^/B\hat s/\sqrt{B}, that of a probability p^\hat p is p^(1−p^)/B\sqrt{\hat p(1 - \hat p)/B}, and that of a standard deviation is above. “It came out 0.370.37” without precision is an anecdote, not a measurement. (Fixing the generator seed is also a matter of reproducibility.)

Implementation from scratch

The function below is the generic simulator: it receives how to generate the population, which statistic to calculate, nn and BB, and returns the simulated sampling distribution, its standard error, and the latter’s Monte Carlo error. It is vectorized by generating the B×nB \times n matrix at once, one sample per row. Use it for a consequential question: among mean, median, and 20 %20\,\% trimmed mean, which has the smallest standard error? Five populations, each with variance 11 for a common comparison.

[ ]Generic sampling-distribution simulatorBrowser
import numpy as np
from scipy import stats

def distribucion_muestral(generador, estadistico, n, B=10000, rng=None):
    """Simula la distribución muestral de un estadístico.
    generador(rng, size) devuelve datos de la población con la forma pedida; estadistico recibe una matriz (B, n)
    (una muestra por fila) y devuelve B valores. Devuelve (valores, error estándar simulado, error Monte Carlo del SE)."""
    rng = np.random.default_rng() if rng is None else rng
    valores = np.asarray(estadistico(generador(rng, (B, n))), dtype=float)
    se = valores.std(ddof=1)
    kurt = stats.kurtosis(valores, fisher=False)            # curtosis (no en exceso) de la distribución muestral
    mc = se * np.sqrt((kurt - 1) / (4 * B))                  # SE del propio SE: sd(ŝ) ≈ τ·√((κ − 1)/(4B))
    return valores, se, mc

s3 = np.sqrt(3)
poblaciones = {                                              # todas con media 0 y varianza 1 (la exponencial, con media 1)
    "normal":         lambda r, size: r.normal(size=size),
    "uniforme":       lambda r, size: r.uniform(-s3, s3, size=size),
    "Laplace":        lambda r, size: r.laplace(scale=1 / np.sqrt(2), size=size),
    "t de Student 3": lambda r, size: r.standard_t(3, size=size) / s3,
    "exponencial":    lambda r, size: r.exponential(size=size),
}
dens_mediana = {"normal": stats.norm.pdf(0), "uniforme": 1 / (2 * s3), "Laplace": 1 / np.sqrt(2),
                "t de Student 3": stats.t.pdf(0, 3) * s3, "exponencial": 0.5}

estadisticos = {
    "media": lambda m: m.mean(axis=1),
    "mediana": lambda m: np.median(m, axis=1),
    "media recortada 20 %": lambda m: stats.trim_mean(m, 0.2, axis=1),
}

n, B = 50, 10000
rng = np.random.default_rng(2024)
print(f"√n·SE simulado (n = {n}, B = {B}); entre paréntesis, el error Monte Carlo de esa cifra")
print(f"{'población':16s}" + "".join(f"{e:>24s}" for e in estadisticos) + "   1/(2f(m)) teórico")
for nombre, gen in poblaciones.items():
    fila = f"{nombre:16s}"
    for est in estadisticos.values():
        _, se, mc = distribucion_muestral(gen, est, n, B, rng)
        fila += f"{se * np.sqrt(n):17.3f} ({mc * np.sqrt(n):.3f})"
    print(fila + f"{1 / (2 * dens_mediana[nombre]):14.3f}")

Multiply by n\sqrt{n} so figures can be compared with asymptotic values. The mean column is 1.001.00 in every population (Monte Carlo error 0.0070.007 to 0.0100.010): SE(Xˉ)=σ/n\mathrm{SE}(\bar X) = \sigma/\sqrt{n} and σ=1\sigma = 1 by construction. The other columns tell the interesting part.

  • No estimator is best for every population. For uniform (no tails) the mean wins easily (1.001.00 versus 1.331.33 for trimmed and 1.691.69 for median). For heavy-tailed laws (Laplace and t3t_3), median and trimmed mean win by 1818 to 28 %28\,\% (0.780.78 and 0.820.82 versus 1.001.00 for Laplace; 0.780.78 and 0.720.72 for t3t_3). For normal the mean is best and median loses that 25 %25\,\% (1.241.24 versus theoretical 1.251.25).
  • The asymptotic formula 1/(2f(m))1/(2f(m)) works reasonably at n=50n = 50: it agrees with simulation to 22 or 33 digits for normal (1.251.25 versus 1.241.24), exponential (1.001.00 and 1.001.00), and t3t_3 (0.7850.785 versus 0.7780.778), with the largest difference for Laplace (0.710.71 versus 0.780.78), whose density peaks at the median and whose asymptotic approximation thus takes longer.
  • The trimmed mean is insurance: it is never worst of the three, best for t3t_3 and exponential, and loses little to the best (7 %7\,\% for normal, 5 %5\,\% for Laplace) except uniform without tails, where it loses 33 %33\,\%. Ranking estimators by variance under different populations is the subject of lesson 4.

Monte Carlo error of 0.0050.005 to 0.0120.012 in the table lets us say 1.241.24 and 1.251.25 are compatible (about two Monte Carlo errors apart, and the formula is only asymptotic), while 0.780.78 and 0.710.71 (Laplace, over ten Monte Carlo errors) are not.

Exact normal theory: χ², t, and F

Everything above applies to any population. With normal data there is a gift: sampling distributions of Xˉ\bar X, S2S^2, and studentized statistic n(Xˉ−μ)/S\sqrt{n}(\bar X - \mu)/S can be calculated exactly for every n≥2n \ge 2, not just as n→∞n \to \infty. Three laws built from the normal are called χ2\chi^2, tt, and FF.

These constructive definitions are useful because they show where the laws come from: a statistic that is a sum of squared normals is χ2\chi^2; a ratio of a normal to the square root of an independent χ2\chi^2 is tt; a ratio of variances is FF. Their densities follow from the module 4 catalog.

Proof

(a) For k=1k = 1: with x>0x > 0, P(Z2≤x)=P(−x≤Z≤x)\Pr(Z^2 \le x) = \Pr(-\sqrt{x} \le Z \le \sqrt{x}), and differentiating gives f(x)=2ϕ(x)⋅12x=x−1/2e−x/22πf(x) = 2\phi(\sqrt{x})\cdot\frac{1}{2\sqrt{x}} = \frac{x^{-1/2}e^{-x/2}}{\sqrt{2\pi}}, the formula at k=1k = 1 because Γ(1/2)=π\Gamma(1/2) = \sqrt{\pi}. The moment generating function is E[esZ2]=(1−2s)−1/2\E[e^{sZ^2}] = (1 - 2s)^{-1/2} for s<1/2s < 1/2. For kk independent summands the product is (1−2s)−k/2(1 - 2s)^{-k/2}, that of Gamma(k/2,scale 2)\mathrm{Gamma}(k/2, \text{scale } 2), and the moment generating function determines the law.

(b) Let independent Z∼N(0,1)Z \sim \Normal(0,1) and V∼χν2V \sim \chi^2_\nu and T=Z/V/νT = Z/\sqrt{V/\nu}. Conditioning on V=vV = v, TT is ZZ multiplied by constant ν/v\sqrt{\nu/v}, with density ϕ(tv/ν)v/ν\phi(t\sqrt{v/\nu})\sqrt{v/\nu}. Integrating against the density of VV,

fν(t)=∫0∞vν/2−1e−v/22ν/2Γ(ν/2)⋅e−t2v/(2ν)2πvν ⁣dv=12ν/2Γ(ν/2)2πν∫0∞vν+12−1e−v2(1+t2/ν) ⁣dv.f_\nu(t) = \int_0^\infty \frac{v^{\nu/2 - 1}e^{-v/2}}{2^{\nu/2}\Gamma(\nu/2)}\cdot\frac{e^{-t^2v/(2\nu)}}{\sqrt{2\pi}}\sqrt{\frac{v}{\nu}}\dd v = \frac{1}{2^{\nu/2}\Gamma(\nu/2)\sqrt{2\pi\nu}}\int_0^\infty v^{\frac{\nu+1}{2} - 1}e^{-\frac{v}{2}(1 + t^2/\nu)}\dd v.

The integral is gamma-type: it equals Γ(ν+12)(21+t2/ν)(ν+1)/2\Gamma\big(\frac{\nu+1}{2}\big)\big(\frac{2}{1 + t^2/\nu}\big)^{(\nu+1)/2}. Simplifying powers of 22 (2(ν+1)/22^{(\nu+1)/2} in numerator, 2ν/222^{\nu/2}\sqrt{2} in denominator) leaves the stated formula.

(c) The same trick: condition on the denominator and integrate a gamma. With a=d1/2a = d_1/2, b=d2/2b = d_2/2, and independent U∼χd12U \sim \chi^2_{d_1} and V∼χd22V \sim \chi^2_{d_2}, ratio W=U/VW = U/V has density fU(wv) vf_U(wv)\,v conditional on V=vV = v, so

fW(w)=∫0∞(wv)a−1e−wv/22aΓ(a)⋅vb−1e−v/22bΓ(b) v ⁣dv=wa−12a+bΓ(a)Γ(b)∫0∞va+b−1e−v2(1+w) ⁣dv=wa−1B(a,b) (1+w)a+b,f_W(w) = \int_0^\infty \frac{(wv)^{a - 1}e^{-wv/2}}{2^{a}\Gamma(a)}\cdot\frac{v^{b - 1}e^{-v/2}}{2^{b}\Gamma(b)}\,v\dd v = \frac{w^{a-1}}{2^{a+b}\Gamma(a)\Gamma(b)}\int_0^\infty v^{a + b - 1}e^{-\frac{v}{2}(1 + w)}\dd v = \frac{w^{a - 1}}{\mathrm{B}(a, b)\,(1 + w)^{a + b}},

because the integral equals Γ(a+b) 2a+b(1+w)−(a+b)\Gamma(a + b)\,2^{a+b}(1 + w)^{-(a+b)}. Since F=d2d1WF = \frac{d_2}{d_1}W, rescaling yields fd1,d2(x)=d1d2fW(d1d2x)f_{d_1, d_2}(x) = \frac{d_1}{d_2}f_W\big(\frac{d_1}{d_2}x\big), the stated formula.

∎

Most-used properties, following from the definitions or density:

  • t1t_1 is the Cauchy, with no mean; tνt_\nu has moments only through order ν−1\nu - 1. For ν>2\nu > 2, Var⁡(T)=ν/(ν−2)\Var(T) = \nu/(\nu - 2). Tails decay as a power, ∣t∣−(ν+1)\abs{t}^{-(\nu + 1)}, not exponentially: tt has heavier tails than the normal.
  • tν→N(0,1)t_\nu \to \Normal(0, 1) as ν→∞\nu \to \infty: because (1+t2/ν)−(ν+1)/2→e−t2/2(1 + t^2/\nu)^{-(\nu+1)/2} \to e^{-t^2/2}, or because V/ν→1V/\nu \to 1 (law of large numbers for VV, a sum of ν\nu iid squares).
  • T2=Z2/(V/ν)∼F1,νT^2 = Z^2/(V/\nu) \sim F_{1, \nu}, and 1/Fd1,d2∼Fd2,d11/F_{d_1, d_2} \sim F_{d_2, d_1}. Thus a two-tailed tt test is a one-tailed FF test.

The fundamental theorem: sample mean and variance

Here is the result making all the above useful.

Proof

A rotation. Let Z=(X−μ1)/σ∼N(0,In)\vb{Z} = (\vb{X} - \mu\vb{1})/\sigma \sim \Normal(\vb{0}, \mat{I}_n). Complete unit vector q1=1/n\vb{q}_1 = \vb{1}/\sqrt{n} to an orthonormal basis q1,…,qn\vb{q}_1, \dots, \vb{q}_n of Rn\R^n (by Gram-Schmidt) and let Q\mat{Q} be the orthogonal matrix with rows qj⊤\vb{q}_j\T. Vector Y=QZ\vb{Y} = \mat{Q}\vb{Z} is Gaussian with mean 0\vb{0} and covariance QInQ⊤=In\mat{Q}\mat{I}_n\mat{Q}\T = \mat{I}_n (affine transformations, or rotational invariance of the standard Gaussian). Its components are therefore Y1,…,Yn∼iidN(0,1)Y_1, \dots, Y_n \iid \Normal(0, 1): for a Gaussian, uncorrelated means independent.

The first coordinate is the mean. Y1=q1⊤Z=1n∑iZi=n (Xˉ−μ)/σY_1 = \vb{q}_1\T\vb{Z} = \frac{1}{\sqrt{n}}\sum_i Z_i = \sqrt{n}\,(\bar X - \mu)/\sigma. It is the projection of Z\vb{Z} onto diagonal 1\vb{1}.

The remaining coordinates are spread. Since Q\mat{Q} preserves norm, ∑iYi2=∑iZi2\sum_i Y_i^2 = \sum_i Z_i^2. And ∑iZi2=∑i(Zi−Zˉ)2+nZˉ2\sum_i Z_i^2 = \sum_i (Z_i - \bar Z)^2 + n\bar Z^2 (decomposition into a part relative to the mean and one for the mean), where nZˉ2=Y12n\bar Z^2 = Y_1^2. Therefore,

∑i=1n(Zi−Zˉ)2=∑j=2nYj2,(n−1)S2σ2=∑i=1n(Zi−Zˉ)2=Y22+⋯+Yn2.\sum_{i=1}^{n}(Z_i - \bar Z)^2 = \sum_{j=2}^{n}Y_j^2, \qquad \frac{(n-1)S^2}{\sigma^2} = \sum_{i=1}^{n}(Z_i - \bar Z)^2 = Y_2^2 + \dots + Y_n^2.

Conclusion. (1) is the affine transformation Xˉ=μ+σY1/n\bar X = \mu + \sigma Y_1/\sqrt{n}. (2) is a sum of n−1n - 1 independent standard normal squares: χn−12\chi^2_{n-1} by definition. (3): Xˉ\bar X is a function of Y1Y_1 and S2S^2 of (Y2,…,Yn)(Y_2, \dots, Y_n), and those coordinates are independent. (4): T=n(Xˉ−μ)/σ[(n−1)S2/σ2]/(n−1)=Y1(Y22+⋯+Yn2)/(n−1)T = \dfrac{\sqrt{n}(\bar X - \mu)/\sigma}{\sqrt{[(n-1)S^2/\sigma^2]/(n-1)}} = \dfrac{Y_1}{\sqrt{(Y_2^2 + \dots + Y_n^2)/(n-1)}}, with Y1∼N(0,1)Y_1 \sim \Normal(0, 1) independent of the denominator’s χn−12\chi^2_{n-1}: this defines tn−1t_{n-1}.

∎

The proof is a rotation. In Rn\R^n, the cloud of samples X\vb{X} is a spherical ball centered at μ1\mu\vb{1}; the coordinate along the diagonal is n Xˉ\sqrt{n}\,\bar X, and (n−1)S2(n - 1)S^2 is squared distance to the diagonal axis. A spherical Gaussian does not distinguish directions (no rotation changes it), so height along the axis and distance from it do not inform one another. See it with n=3n = 3, the smallest dimension with something to see.

InteractiveWhy X̄ and S² are independent
900 samples (X1,X2,X3)(X_1, X_2, X_3) as points in R3\R^3
x₁x₂x₃diagonal (1,1,1)
  • samples in the Xˉ\bar X band
  • remaining samples
  • diagonal: Xˉ\bar X increases along it
Each sample: Xˉ\bar X (horizontal) versus S2S^2 (vertical)
Distribution of S2S^2 inside and outside the band
  • S2S^2 inside the band
  • S2S^2 outside the band
  • theory: S2∼Exp(1)S^2 \sim \mathrm{Exp}(1) (n = 3)
Population of each XiX_i (mean 0, variance 1)
0.60
38°
22°
corr(Xˉ,S2)\mathrm{corr}(\bar X, S^2)0.046
corr((Xˉ−μ)2,S2)\mathrm{corr}((\bar X-\mu)^2, S^2)−0.019
Mean S2S^2 inside / outside the band1.02 / 0.97
Kolmogorov distance DD (inside versus outside)0.075 (5 % threshold: 0.126)
Points in the band137 of 900
Each point is a sample (X1,X2,X3)(X_1, X_2, X_3). The violet diagonal is direction (1,1,1)(1, 1, 1): height along it is 3 Xˉ\sqrt{3}\,\bar X and distance from it is 2S2\sqrt{2S^2}. Drag to rotate the cloud (or use sliders or view buttons). The orange band selects samples with Xˉ\bar X in an interval. On the right, above: each sample's (Xˉ,S2)(\bar X, S^2) scatterplot; below: the distribution of S2S^2 inside versus outside the band. Does the S2S^2 distribution change as the band moves? Not for normal; switch to 'Exponential' and 'Uniform' and inspect cloud shape and readouts.

What you should have seen:

  • For normal, the cloud is a ball from every view. Looking along the diagonal (“Along the diagonal”) it is a round disk, and from the side (“Vertical diagonal”) the same disk: the cloud is spherical without preferred direction. The S2S^2 distribution inside the band matches outside regardless of band center: mean S2S^2 is around 11 everywhere (the band captures from about 3030 samples at extremes to 260260 at the center, so mean noise ranges from ±0.06\pm 0.06 to ±0.2\pm 0.2), and Kolmogorov distance between the two usually stays below the 5 %5\,\% threshold. Also S2S^2 follows an exponential of mean 11 (χ22/2\chi^2_2/2 with n=3n = 3, dashed line).
  • For exponential, the cloud has three tails, one per axis, and is round from no view. With centered coordinates, the vertex is at (−1,−1,−1)(-1, -1, -1) (the minimum possible), and the Xˉ\bar X band changes the S2S^2 distribution. With Xˉ\bar X near its minimum, all three observations hug the floor and S2S^2 is nearly zero; with high Xˉ\bar X one observation must be huge and S2S^2 is large. This can be calculated exactly: conditional on the sum, an exponential sample is uniform on the simplex, yielding E[S2∣Xˉ]=34(Xˉ+1)2\E[S^2 \given \bar X] = \tfrac34(\bar X + 1)^2 in centered coordinates, equal to 0.030.03 at Xˉ=−0.8\bar X = -0.8 and 3.63.6 at Xˉ=1.2\bar X = 1.2 (the 0.40.4-wide band averages this value: it gives 0.060.06 and 3.73.7). Readouts reflect it: corr(Xˉ,S2)≈0.67\mathrm{corr}(\bar X, S^2) \approx 0.67 at n=3n = 3 (0.690.69 at n=8n = 8 in the cell below).
  • Uncorrelated is insufficient, illustrated by uniform. Uniform is symmetric, so corr(Xˉ,S2)≈0\mathrm{corr}(\bar X, S^2) \approx 0 (the readout is near zero), but they are not independent: as Xˉ\bar X approaches an extreme (±3\pm\sqrt{3}, with Xi∈[−3,3]X_i \in [-\sqrt{3}, \sqrt{3}]) all data press against the edge and S2S^2 is small, so E[S2∣Xˉ≈1.2]≈0.21\E[S^2 \given \bar X \approx 1.2] \approx 0.21, versus 1.251.25 at Xˉ≈0\bar X \approx 0 (the band gives 0.220.22 and 1.291.29). Readout corr((Xˉ−μ)2,S2)≈−0.41\mathrm{corr}((\bar X - \mu)^2, S^2) \approx -0.41 detects that nonlinear dependence, and Kolmogorov distance comparing full distributions confirms it.
  • What normality is. Independence of Xˉ\bar X and S2S^2 characterizes the normal (Geary-Lukacs theorem): if for iid samples from a finite-variance law Xˉ\bar X and S2S^2 are independent, the law is normal. This is related to Maxwell’s (or Herschel-Maxwell) characterization: among laws with independent coordinates, only the centered Gaussian yields a spherical, rotation-invariant cloud.

One final step, FF. Given two independent normal samples of sizes n1,n2n_1, n_2 and variances σ12,σ22\sigma_1^2, \sigma_2^2, then S12/σ12S22/σ22∼Fn1−1, n2−1\dfrac{S_1^2/\sigma_1^2}{S_2^2/\sigma_2^2} \sim F_{n_1 - 1,\, n_2 - 1}, by theorem part (2) and the definition of FF. This gives the variance-equality test, and in the linear model (module 5, lesson 19) the regression-significance FF.

Numerical verification

Check all this experimentally. Simulate B=40000B = 40000 samples of n=8n = 8 normals with μ=3\mu = 3 and σ=2\sigma = 2, and compare (n−1)S2/σ2(n-1)S^2/\sigma^2 with χ72\chi^2_7 and the tt statistic with t7t_7, using densities written from scratch from the theorem’s formulas (no scipy.stats in density calculations) and trapezoidal integration. Then check independence with three populations.

[ ]Numerical verification of normal theoryBrowser
import numpy as np
from math import lgamma, log, pi
from scipy import stats

def densidad_chi2(x, k):
    """χ²_k desde la definición como Gamma(k/2, escala 2)."""
    return np.exp((k / 2 - 1) * np.log(x) - x / 2 - (k / 2) * log(2) - lgamma(k / 2))

def densidad_t(x, nu):
    """t de Student: la fórmula que se deduce en la lección."""
    c = lgamma((nu + 1) / 2) - lgamma(nu / 2) - 0.5 * log(nu * pi)
    return np.exp(c - (nu + 1) / 2 * np.log1p(x ** 2 / nu))

def prob_numerica(dens, a, b, m=4001):
    """∫ dens entre a y b por la regla del trapecio (suficiente aquí)."""
    x = np.linspace(a, b, m)
    y = dens(x)
    return float(np.sum((y[1:] + y[:-1]) / 2 * np.diff(x)))

rng = np.random.default_rng(7)
n, B = 8, 40000
mu, sigma = 3.0, 2.0
X = rng.normal(mu, sigma, size=(B, n))
xbar, s2 = X.mean(axis=1), X.var(axis=1, ddof=1)
Q = (n - 1) * s2 / sigma ** 2                          # debería ser χ² con n−1 = 7 grados de libertad
T = np.sqrt(n) * (xbar - mu) / np.sqrt(s2)             # debería ser t con 7 grados de libertad

print("χ²_7: media %.3f (teoría 7), varianza %.3f (teoría 14)" % (Q.mean(), Q.var()))
for a, b in [(0, 4), (4, 10), (10, 40)]:
    print(f"  P({a} < Q < {b}): simulada {np.mean((Q > a) & (Q < b)):.4f}   integral de mi densidad {prob_numerica(lambda x: densidad_chi2(x, 7), max(a, 1e-9), b):.4f}")
print("t_7: P(|T| > 2.5): simulada %.4f   integral de mi densidad %.4f" % (np.mean(np.abs(T) > 2.5), 1 - 2 * prob_numerica(lambda x: densidad_t(x, 7), 0, 2.5)))
print("p-valor de Kolmogorov-Smirnov frente a χ²_7: %.3f, frente a t_7: %.3f" % (stats.kstest(Q, "chi2", args=(7,)).pvalue, stats.kstest(T, "t", args=(7,)).pvalue))

def correlaciones(gen, mu, B=200000, n=8):
    """corr(X̄, S²) y corr((X̄−μ)², S²) con B muestras de tamaño n."""
    x = gen((B, n))
    m, v = x.mean(axis=1), x.var(axis=1, ddof=1)
    return np.corrcoef(m, v)[0, 1], np.corrcoef((m - mu) ** 2, v)[0, 1]

print("\n                corr(X̄, S²)   corr((X̄−μ)², S²)")
for nombre, gen, m0 in [("normal", lambda s: rng.normal(size=s), 0.0),
                        ("uniforme", lambda s: rng.uniform(size=s), 0.5),
                        ("exponencial", lambda s: rng.exponential(size=s), 1.0)]:
    r1, r2 = correlaciones(gen, m0)
    print(f"{nombre:12s} {r1:12.3f} {r2:16.3f}")

The output says: simulated χ72\chi^2_7 has mean 6.986.98 and variance 14.0214.02 (theory: 77 and 1414), interval probabilities agree with integration of the scratch-written density to two or three digits (Monte Carlo error with B=40000B = 40000 is ±0.002\pm 0.002), tail P(∣T∣>2.5)\Pr(\abs{T} > 2.5) is 0.0400.040 simulated and 0.0410.041 by integration, and neither Kolmogorov-Smirnov test rejects (p=0.28p = 0.28 and 0.990.99). The last table is the figure in numbers: for normal, both correlations are zero (−0.002-0.002 and 0.0040.004); for uniform, linear is zero and nonlinear is −0.30-0.30 (at n=8n = 8); for exponential, both are clearly positive (0.690.69 and 0.450.45).

Studentization: why the normal becomes a t

In practice σ\sigma is unknown. If it were known, n(Xˉ−μ)/σ∼N(0,1)\sqrt{n}(\bar X - \mu)/\sigma \sim \Normal(0, 1) exactly and interval Xˉ±1.96 σ/n\bar X \pm 1.96\,\sigma/\sqrt{n} would cover μ\mu with probability exactly 0.950.95. Replacing σ\sigma with SS is studentization (after “Student”), and the ratio’s law ceases to be normal: it is tn−1t_{n-1} by Fisher’s theorem. The difference is two sources of randomness: numerator Xˉ−μ\bar X - \mu and denominator SS. When SS happens to be small, the ratio shoots up, and this fluctuation fattens the tails.

The correction is simple: use quantile tn−1,0.975t_{n-1, 0.975} instead of 1.961.96. For n=10n = 10 (nine degrees of freedom) it is 2.2622.262, 15 %15\,\% more. Coverage of the z=1.96z = 1.96 interval falls short and is calculated exactly: 2Ftn−1(1.96)−12F_{t_{n-1}}(1.96) - 1.

InteractiveStudent's t and its tails
Density of t4t_{4} versus N(0,1)\Normal(0, 1)
1.962.78
  • t4t_{4}
  • N(0,1)\Normal(0, 1)
  • tails beyond ±1.96\pm 1.96
Actual coverage of a “95 %” interval versus nn
nominal level 0.95
  • with zz: exact (normal data)
  • with zz: simulated, selected population
  • with tt quantile: simulated
30 intervals Xˉ±1.96 S/n\bar X \pm 1.96\,S/\sqrt{n} from simulated samples: 2 miss μ=0\mu = 0 (normal data would predict 3.6)
  • covers true mean
  • does not cover it
5
Data population (mean 0, variance 1)
Intervals in lower panel
t4, 0.975t_{4,\,0.975} quantile (versus z=1.96z = 1.96)2.776
P(∣T4∣>1.96)\Pr(\abs{T_{4}} > 1.96), normal data0.1216
Exact zz interval coverage (normal)0.8784
Simulated zz coverage (4000 samples, ± 0.003)0.883
Simulated coverage with tt quantile0.953
Left: tn−1t_{n-1} density versus normal, with tail mass beyond ±1.96\pm 1.96 and quantile tn−1,0.975t_{n-1, 0.975}. Right: actual coverage of Xˉ±1.96 S/n\bar X \pm 1.96\,S/\sqrt{n} versus nn, exact for normal data (dashed) and simulated for the chosen population (orange points), alongside coverage of the interval using the tt quantile (teal). Below: 30 actual intervals. From what nn can we forget tt? What if data are not normal? Reduce nn to 33, then switch to 'Exponential' at n=10n = 10.

What you should have seen:

  • With small nn the difference is huge. At n=3n = 3 (ν=2\nu = 2) the quantile is 4.3034.303 and zz-interval coverage falls to 0.8110.811: intervals advertised as “95 %95\,\%” fail almost one time in five. At n=5n = 5, 0.8780.878; n=10n = 10, 0.9180.918; n=20n = 20, 0.9350.935; n=30n = 30, 0.9400.940 and n=100n = 100, 0.9470.947. The correction disappears slowly: coverage error is order 1/n1/n.
  • The tt tail is responsible. P(∣Tν∣>1.96)\Pr(\abs{T_{\nu}} > 1.96) is 0.300.30 for ν=1\nu = 1 (Cauchy), 0.190.19 for ν=2\nu = 2, 0.120.12 for ν=4\nu = 4, 0.0820.082 for ν=9\nu = 9, and 0.0530.053 for ν=99\nu = 99. Normal gives 0.050.05.
  • Studentization is not the whole story. With exponential (skewed) data and n=10n = 10, even the tt-quantile interval covers only 0.900.90 (and zz covers 0.870.87). Exact theory assumes normality: when it fails, Xˉ\bar X and SS are no longer independent (as the preceding figure showed), and the ratio is no longer tt. At n=30n = 30 coverage is 0.9270.927 (tt) and 0.9180.918 (zz) for exponentials, and at n=100n = 100, 0.9420.942 and 0.9390.939. The CLT and Slutsky’s lemma (continuous mapping) guarantee T→dN(0,1)T \xrightarrow{d} \Normal(0, 1) for any finite-variance population, but not the rate; that depends on skewness, as seen in the CLT.
  • Degrees of freedom. n−1n - 1 is not magic. ∑i(Xi−Xˉ)2\sum_i (X_i - \bar X)^2 is squared norm of residual vector X−Xˉ1\vb{X} - \bar X\vb{1}, living in the subspace orthogonal to 1\vb{1} (dimension n−1n - 1): one degree of freedom was spent estimating μ\mu. It is the same n−1n - 1 as in unbiasedness of S2S^2, returning in the linear model as n−pn - p with pp estimated parameters.

With libraries

scipy.stats implements all three laws with pdf, cdf, ppf (quantiles), and rvs (samples). The next cell checks what we saw: tt quantiles approach 1.961.96, relationships between laws (T2∼F1,νT^2 \sim F_{1,\nu} and 1/Fd1,d2∼Fd2,d11/F_{d_1,d_2} \sim F_{d_2,d_1}), and coverage of pivot-based intervals. Besides one for the mean using tt, there is one for σ2\sigma^2 using χ2\chi^2, an example of a good pivot yielding an interval.

[ ]Normal theory with scipy.statsBrowser
import numpy as np
from scipy import stats

# 1) Cuantiles: la t se acerca a la normal desde fuera
print(f"{'ν':>5s} {'t_0.975':>9s} {'P(|T|>1.96)':>12s}")
for nu in (1, 2, 4, 9, 29, 99, 1000):
    print(f"{nu:5d} {stats.t.ppf(0.975, nu):9.3f} {2 * stats.t.sf(1.96, nu):12.4f}")
print(f"{'∞':>5s} {stats.norm.ppf(0.975):9.3f} {2 * stats.norm.sf(1.96):12.4f}")

# 2) Relaciones entre las tres leyes: T² ~ F(1, ν) y 1/F(d1, d2) ~ F(d2, d1)
nu = 7
print("\nT²~F(1,7):  t.ppf(0.975, 7)² = %.5f   f.ppf(0.95, 1, 7) = %.5f" % (stats.t.ppf(0.975, nu) ** 2, stats.f.ppf(0.95, 1, nu)))
print("1/F(4,9):   1/f.ppf(0.05, 4, 9) = %.5f   f.ppf(0.95, 9, 4) = %.5f" % (1 / stats.f.ppf(0.05, 4, 9), stats.f.ppf(0.95, 9, 4)))

# 3) Cobertura de dos intervalos al 95 % para una media y una varianza normales (n = 10, 20000 muestras)
rng = np.random.default_rng(11)
n, B, mu, sigma = 10, 20000, 5.0, 3.0
X = rng.normal(mu, sigma, (B, n))
xbar, s = X.mean(axis=1), X.std(axis=1, ddof=1)
q = stats.t.ppf(0.975, n - 1)
cubre_mu = np.abs(xbar - mu) <= q * s / np.sqrt(n)
cubre_z = np.abs(xbar - mu) <= 1.96 * s / np.sqrt(n)
lo = (n - 1) * s ** 2 / stats.chi2.ppf(0.975, n - 1)         # (n−1)S²/σ² ~ χ²_{n−1}: pivote para σ²
hi = (n - 1) * s ** 2 / stats.chi2.ppf(0.025, n - 1)
cubre_var = (lo <= sigma ** 2) & (sigma ** 2 <= hi)
print(f"\ncobertura del intervalo de μ con t (q = {q:.3f}):   {cubre_mu.mean():.4f}")
print(f"cobertura del intervalo de μ con z = 1.96:        {cubre_z.mean():.4f}   (exacta: {2 * stats.t.cdf(1.96, n - 1) - 1:.4f})")
print(f"cobertura del intervalo de σ² con χ²:             {cubre_var.mean():.4f}")

# 4) Y con datos exponenciales (asimétricos) la t de n = 10 ya no es exacta
Xe = rng.exponential(1.0, (B, n))
xe, se = Xe.mean(axis=1), Xe.std(axis=1, ddof=1)
print(f"cobertura del intervalo con t para datos exponenciales, n = 10:   {np.mean(np.abs(xe - 1) <= q * se / np.sqrt(n)):.4f}")

The first table is the figure’s number column. Both identities in the second part hold to five digits: they are exact identities, not simulations. The third checks the theory’s promise: the tt interval covers μ\mu 95.0 %95.0\,\% of the time, the zz interval 92.0 %92.0\,\% (exact coverage is 91.84 %91.84\,\%, and simulated has error ±0.2\pm 0.2 points), and the σ2\sigma^2 interval based on the χn−12\chi^2_{n-1} pivot covers 95.1 %95.1\,\%. The final line, for exponential data, gives 0.900.90: exact theory is a property of normality, not of tt.

Common mistakes

Exercises

ProofIndependence of X̄ and S² by projections
Prove: Let X1,…,Xn∼iidN(μ,σ2)X_1, \dots, X_n \iid \Normal(\mu, \sigma^2) with n≥2n \ge 2. Prove that Xˉ\bar X and S2S^2 are independent and (n−1)S2/σ2∼χn−12(n - 1)S^2/\sigma^2 \sim \chi^2_{n-1}, using the orthogonal projection matrix P=1n11⊤\mat{P} = \frac{1}{n}\vb{1}\vb{1}\T onto the diagonal instead of constructing a full basis.
0
Let Z=(X−μ1)/σ∼N(0,In)\vb{Z} = (\vb{X} - \mu\vb{1})/\sigma \sim \Normal(\vb{0}, \mat{I}_n). Note P\mat{P} is symmetric and idempotent of rank 11, and I−P\mat{I} - \mat{P} is orthogonal projection onto the orthogonal complement of 1\vb{1}, of dimension n−1n - 1.

Step 1 of 5. How are Xˉ\bar X and the residual vector expressed in terms of P\mat{P}?

NumericStandard error of a mean
A set of n=400n = 400 latencies (milliseconds) has mean 85.285.2 and sample standard deviation S=12S = 12. What is the estimated standard error of the mean, in milliseconds?
NumericActual coverage of the z interval
For a normal sample of n=5n = 5 observations and unknown σ\sigma, construct interval Xˉ±1.96 S/n\bar X \pm 1.96\,S/\sqrt{n} (with z=1.96z = 1.96 instead of the tt quantile). What is its actual probability of covering μ\mu?
NumericHow many replicates are needed?
A statistic with approximately normal sampling distribution is simulated and its standard error estimated by the standard deviation of BB replicates. How many replicates BB are needed for the relative error of this simulated standard error to be 1 %1\,\% (estimator standard deviation equal to 0.010.01 times the estimated value)? Use 1/2(B−1)1/\sqrt{2(B - 1)}.
QuizWhich models are not identifiable?
Which of these models have a nonidentifiable parameter in the stated parameterization?

More than one answer may be correct.

QuizWhat does the error bar represent?
A report shows mean metric for two models over n=25n = 25 runs with error bars. Repeating the study with n=100n = 100 runs per model, what should happen?
CodeStandard error of the median by simulation
Implement se_mediana(generador, n, B=4000, seed=0): simulate B samples of size n with generador(rng, size) (which returns population data of shape size, with rng a numpy.random.Generator), compute each sample median, and return the standard deviation of those B medians (with ddof=1). Use np.random.default_rng(seed). Tests check that, for n = 200, it approximates 1/(2f(m)n)1/(2f(m)\sqrt{n}) in several populations.
import numpy as np

def se_mediana(generador, n, B=4000, seed=0):
  # generador(rng, size) -> datos de la población con forma size
  # devuelve la desviación típica (ddof=1) de las B medianas
  pass
Shift+Enter to run

Summary

Key idea
A statistical model is a family of laws {Pθ:θ∈Θ}\{P_\theta : \theta \in \Theta\} (parametric, semiparametric, or nonparametric), and a parameter can be learned from data only if identifiable: θ↦Pθ\theta \mapsto P_\theta is injective. Without identifiability no estimator can be consistent across the model (ridge ab=cab = c of y=abx+εy = abx + \varepsilon is the example; reparameterize by cc). A statistic is a function of data not depending on θ\theta, and its sampling distribution describes variation on repeating the experiment. Its standard deviation is standard error: σ/n\sigma/\sqrt{n} for the mean (the −1/2-1/2 slope in simulation), asymptotic 1/(2f(m)n)1/(2f(m)\sqrt{n}) for the median, and it is not data spread. When no formula exists, simulate (generate, calculate, repeat), with Monte Carlo error decreasing as 1/B1/\sqrt{B}: 1/2B1/\sqrt{2B} relative error for a normal SE. For normal data the sampling distribution is exact: an orthogonal rotation with first row 1/n\vb{1}/\sqrt{n} gives Xˉ⊥ ⁣ ⁣ ⁣⊥S2\bar X \indep S^2, (n−1)S2/σ2∼χn−12(n-1)S^2/\sigma^2 \sim \chi^2_{n-1}, and n(Xˉ−μ)/S∼tn−1\sqrt{n}(\bar X - \mu)/S \sim t_{n-1}, with heavier tails than normal. Thus a z=1.96z = 1.96 interval covers 87.8 %87.8\,\% at n=5n = 5, and tt is insufficient if data are not normal.