Module contents
Lesson 26 of 27Core 95 min

Uncertainty analysis, propagation and communication

Quantify uncertainty around a number. Propagate it through functions of several quantities with linear rules and Monte Carlo, distinguish confidence, prediction and tolerance intervals, combine estimates with inverse-variance weighting and model heterogeneity, and communicate the resulting uncertainty.

After this lesson you can

  • Propagate uncertainty using a linear approximation with covariances and using Monte Carlo, and diagnose when linearization fails.
  • Compute tolerance intervals and identify when they answer the question better than confidence or prediction intervals.
  • Combine independent estimates with inverse-variance weighting and estimate between-source heterogeneity with DerSimonian–Laird and I².
  • Choose and label error bars as standard deviations, standard errors or intervals, and interpret overlap correctly.
  • Report estimates, intervals, assumptions and sources of unquantified uncertainty.

Before you start

Motivation: a single number is not a result

A security manager must budget the expected annual cost of incidents for a service. The model is as simple as it looks: L=λ⋅c⋅rL = \lambda \cdot c \cdot r, with λ\lambda incidents per year, cc the average cost of each, and rr the fraction of risk the current control does not eliminate. None of the three factors is known: λ\lambda comes from counting past incidents, cc from a small sample of costs, and rr from expert judgment. This is the pattern throughout: a quantity of interest that is a function of several uncertain quantities. The same applies to latency of a composite service (a sum of stages with different distributions) or model performance measured on several evaluation sets.

The next cell’s figures are illustrative, not from a real system. First, what a hurried report would do: multiply point estimates. Then, what this lesson teaches: propagate uncertainty in each ingredient to the answer.

[ ]A single figure versus propagating uncertainty in three factorsBrowser
import numpy as np

rng = np.random.default_rng(26)
M = 1_000_000

# Ingredientes (cifras didácticas): incidentes por año, coste medio por incidente (k€) y fracción de riesgo que no elimina el control
lam_hat, u_lam = 2.0, np.sqrt(6) / 3        # 6 incidentes en 3 años: tasa 2 por año, incertidumbre de Poisson sqrt(k)/T
c_hat, u_c = 85.0, 18.0                      # k€, a partir de 12 incidentes pasados
r_hat, u_r = 0.40, 0.10                      # juicio de expertos: 1 - eficacia del control

L_hat = lam_hat * c_hat * r_hat
rel = np.sqrt((u_lam / lam_hat) ** 2 + (u_c / c_hat) ** 2 + (u_r / r_hat) ** 2)
u_L = L_hat * rel
print(f"cifra única:  L = {L_hat:.1f} k€ al año")
print(f"ley lineal:   u = {u_L:.1f} k€ ({100 * rel:.0f} %), intervalo al 95 %: [{L_hat - 1.96 * u_L:.1f}, {L_hat + 1.96 * u_L:.1f}]")

# Monte Carlo con distribuciones que respetan el dominio de cada magnitud (positiva, positiva, en [0, 1])
lam = rng.gamma(6, 1 / 3, M)                                   # media 2, desviación típica sqrt(6)/3
s2 = np.log(1 + (u_c / c_hat) ** 2)
c = rng.lognormal(np.log(c_hat) - s2 / 2, np.sqrt(s2), M)      # media 85, desviación típica 18
kb = r_hat * (1 - r_hat) / u_r ** 2 - 1
r = rng.beta(r_hat * kb, (1 - r_hat) * kb, M)                  # media 0.40, desviación típica 0.10
L = lam * c * r
lo, med, hi = np.percentile(L, [2.5, 50, 97.5])
print(f"Monte Carlo:  media {L.mean():.1f}, desviación típica {L.std():.1f}, mediana {med:.1f}")
print(f"              intervalo al 95 %: [{lo:.1f}, {hi:.1f}]")
print(f"P(L > 100 k€) = {np.mean(L > 100):.3f};  P(L > extremo superior lineal) = {np.mean(L > L_hat + 1.96 * u_L):.3f}")

The single figure, 6868 k€, is correct as a central value and misleading as a summary. The linear law gets the spread right (about 3636 k€) but draws a symmetric interval reaching −1.8-1.8 k€: a negative cost the model does not allow. Monte Carlo, using distributions respecting the domain, gives an asymmetric interval, [19.0,159.9][19.0, 159.9]: true risk is shifted upward and the probability of exceeding 100100 k€ is almost one in six, information neither the single figure nor the linear law contains. This lesson builds both tools (linear law and Monte Carlo), teaches when to trust each, and closes with three parts of the craft: choosing the interval that answers the question (confidence, prediction or tolerance), combining estimates from different sources, and communicating results without misleading.

We use without further explanation standard error, confidence and prediction intervals, the delta method, nonparametric bootstrap, simulation studies and effect size, as well as the covariance matrix, gradient and linearization.

Three kinds of uncertainty and two ways to evaluate it

Not all uncertainty in a result is of the same kind; mixing kinds is a major source of misleading reports.

  • Sampling. Comes from observing a finite sample from a varying process. It decreases as nn grows, typically like 1/n1/\sqrt{n}, and is studied by the module’s classical inference.
  • Measurement. Comes from the instrument: resolution, calibration, drift. Repeating measurement does not reduce it if the defect is the same every time (a clock with constant offset carries it into every reading).
  • Model. Comes from potentially false functional form or assumptions: independence, distribution, relationships between quantities. No sample from the model itself quantifies it; explore it by model comparison and sensitivity analysis, and disclose it if not quantified.

The GUM (Guide to the expression of uncertainty in measurement, JCGM 100:2008), the international metrology standard, adds a practical distinction about how each component is evaluated, distinct from “random versus systematic”.

The table lists common type-B conversions. They come from calculating each distribution’s variance: a uniform distribution on [−a,a][-a, a] has variance a2/3a^2/3, and a symmetric triangular distribution with the same half-width has a2/6a^2/6 (less dispersed because it concentrates mass at the center).

Available informationAssigned distributionuu
Value within ±a\pm a, nothing else knownuniforma/3a/\sqrt{3}
Value within ±a\pm a, central values more likelytriangulara/6a/\sqrt{6}
Certificate: ±U\pm U with coverage factor kknormalU/kU/k
Digital resolution δ\delta (last digit)uniform with a=δ/2a = \delta/2δ/(23)\delta/(2\sqrt{3})
kk Poisson events in time TTestimated rate k/Tk/Tk/T\sqrt{k}/T

Independent components combine in quadrature, uc2=∑iui2u_c^2 = \sum_i u_i^2 (later we see the rule with sensitivities and correlations), and the result is expressed using expanded uncertainty U=k ucU = k\,u_c, where coverage factor kk must be the quantile of an tt with Welch–Satterthwaite effective degrees of freedom:

νef=uc4∑iui4/νi,\nu_{\text{ef}} = \frac{u_c^4}{\sum_i u_i^4/\nu_i},

where type-B components with solid information count as νi=∞\nu_i = \infty. The value k=2k = 2 is merely customary for large νef\nu_{\text{ef}}. The next cell builds a latency measurement’s budget with three components.

[ ]Latency uncertainty budget: type A and B componentsBrowser
import numpy as np
from scipy import stats

# 10 lecturas con un cronómetro: media 25.40 ms y desviación típica 0.45 ms (tipo A)
n, xbar, s = 10, 25.40, 0.45
comp = {
    "repetibilidad (tipo A)":            (s / np.sqrt(n), n - 1),                 # u = s / sqrt(n), nu = 9
    "resolución 0.1 ms (tipo B, unif.)": (0.1 / (2 * np.sqrt(3)), np.inf),        # a = 0.05
    "calibración ±0.30 ms, k = 2 (B)":   (0.30 / 2, np.inf),
}
uc2 = sum(u ** 2 for u, _ in comp.values())
uc = np.sqrt(uc2)
denom = sum(u ** 4 / nu for u, nu in comp.values())
nu_ef = uc ** 4 / denom
k = stats.t.ppf(0.975, nu_ef)
for nombre, (u, nu) in comp.items():
    print(f"{nombre:36s} u = {u:.4f} ms   {100 * u ** 2 / uc2:5.1f} % de u_c^2")
print(f"u_c = {uc:.4f} ms, grados de libertad efectivos = {nu_ef:.1f}, k = {k:.3f}, U = {k * uc:.3f} ms")
print(f"resultado: {xbar:.2f} ± {k * uc:.2f} ms (k = {k:.2f}, nivel aproximado 95 %)")

Two observations: repeatability and calibration dominate while clock resolution hardly matters, which the budget shows and intuition does not; and since the type-A component, the only one with few degrees of freedom (ν=9\nu = 9), contributes almost half the variance, effective degrees of freedom fall to about 4242 and the coverage factor is 2.022.02, not exactly 22. With only three readings, the same calculation would give a much larger factor.

Linear propagation law

Given Y=f(X1,…,Xp)Y = f(X_1, \dots, X_p) with inputs of known uncertainty, we want the uncertainty of YY. Start by visualizing it.

InteractiveLinear propagation versus Monte Carlo
Inputs (A,B)(A, B) and contours of f=A/Bf=A/B
B = 0
Distribution of ff in 20,000 draws
The axis clips the tails: 0.3 % of draws fall outside.
  • input draws and their 95% ellipse
  • true contour of ff
  • linear model: contour lines and predicted normal
  • linear 95% interval
  • Monte Carlo 95% interval
Function of the two quantities
8 %
28 %
0.00
Nominal value f=A/Bf=A/B2.00
Standard uncertainty: linear law | Monte Carlo0.58 | 1.82
Contributions to u2u^2: AA | BB | covariance8 % | 92 % | 0 %
95% interval: linear[0.86, 3.14]
95% interval: Monte Carlo (percentiles)[1.25, 4.51]
Actual coverage of the linear interval89.7 %
Linearization fails. The linear interval [0.86, 3.14] contains 89.7 % of draws, not 95%; the Monte Carlo interval is [1.25, 4.51] (quantile skew 0.54, simulated mean differs 10.6 % from nominal).
Two normal quantities AA and BB and a function of both. At left, input draws, the ellipse containing 95 %, and in aquamarine the true level curves of ff at the nominal value and endpoints of the linear interval; dashed violet lines show what the linear law sees: parallel straight lines. At right, the histogram of ff from 20 000 draws, the normal predicted by the linear law (dashed violet), and both 95 % intervals. With the ratio, increase uncertainty in BB until curves separate from lines. With the product, move ρ\rho from −0.95-0.95 to 0.950.95 and see how much uu changes. With AeBAe^{B}, verify that asymmetry appears even though BB is perfectly symmetric.

The linear law replaces ff by its tangent plane at the nominal value. In the left figure this turns level curves of ff into parallel lines: the linear interval is exact when curves are straight and fails to the extent they curve inside the input ellipse. With A/BA/B, level curves are straight lines fanning out from the origin: the smaller BB, the faster ff changes, so the symmetric linear interval falls short above and extends too far below.

Proof

The first two statements are properties of a linear form: E[X−μ]=0\E[\vb{X} - \vb{\mu}] = \vb{0} and Var⁡(g⊤W)=g⊤Cov⁡(W)g\Var(\vb{g}\T\vb{W}) = \vb{g}\T\Cov(\vb{W})\vb{g}. For the third, Taylor’s theorem with Lagrange remainder gives, for each realization, Y−Y^=12(X−μ)⊤∇2f(ξ)(X−μ)Y - \hat{Y} = \tfrac{1}{2}(\vb{X} - \vb{\mu})\T\hess f(\vb{\xi})(\vb{X} - \vb{\mu}) with ξ\vb{\xi} on the segment joining μ\vb{\mu} and X\vb{X}, hence ∣Y−Y^∣≤L2∥X−μ∥2\abs{Y - \hat{Y}} \le \tfrac{L}{2}\norm{\vb{X} - \vb{\mu}}^2. Standard deviation is the L2L^2 norm of the centered variable, and centering does not increase the norm, so by Minkowski’s triangle inequality

∣sd⁡(Y)−sd⁡(Y^)∣≤sd⁡(Y−Y^)≤(E[(Y−Y^)2])1/2≤L2(E∥X−μ∥4)1/2.\big|\operatorname{sd}(Y) - \operatorname{sd}(\hat{Y})\big| \le \operatorname{sd}(Y - \hat{Y}) \le \big(\E[(Y - \hat{Y})^2]\big)^{1/2} \le \frac{L}{2}\big(\E\norm{\vb{X} - \vb{\mu}}^4\big)^{1/2}.

If X−μ=σZ\vb{X} - \vb{\mu} = \sigma\vb{Z}, the right side is σ2L (E∥Z∥4)1/2/2\sigma^2 L\,(\E\norm{\vb{Z}}^4)^{1/2}/2, of order σ2\sigma^2, while sd⁡(Y^)\operatorname{sd}(\hat{Y}) is of order σ\sigma.

∎

This is the delta-method argument, except that here there is no n→∞n \to \infty: the small parameter is relative input dispersion. It shows where the law fails: the bound grows with curvature LL and the inputs’ fourth moment. Two theorem conditions fail in examples that matter. The Hessian of A/BA/B is unbounded near B=0B = 0, and that of eBe^B grows with BB. If BB is normal, A/BA/B has neither finite mean nor variance, because 1/B1/B has a nonintegrable singularity at B=0B = 0: a Monte Carlo standard deviation is then meaningless and changes between runs (check the figure: with BB at 50 %50\,\%, the “Monte Carlo uu” jumps between configurations, unlike percentiles). A coverage interval is well defined, so Monte Carlo reports it.

Special cases worth remembering

With coefficients ci=∂f/∂xic_i = \partial f/\partial x_i and correlations ρij\rho_{ij}, expanding g⊤Σg\vb{g}\T\mat{\Sigma}\vb{g} gives

u2(Y)=∑ici2ui2+2∑i<jcicj ρij uiuj.u^2(Y) = \sum_i c_i^2 u_i^2 + 2\sum_{i<j} c_i c_j\,\rho_{ij}\,u_i u_j .
  • Sum or difference, Y=X1±X2Y = X_1 \pm X_2: u2=u12+u22±2ρu1u2u^2 = u_1^2 + u_2^2 \pm 2\rho u_1 u_2. With ρ>0\rho > 0, the sum has more uncertainty than quadrature and the difference less. Two latencies measured with the same clock share its offset: the difference cancels it, the sum doubles it.
  • Products and ratios, Y=κ∏iXiaiY = \kappa\prod_i X_i^{a_i}: since ∂ln⁡Y/∂xi=ai/xi\partial \ln Y/\partial x_i = a_i/x_i, with δi=ui/∣μi∣\delta_i = u_i/\abs{\mu_i},
(u(Y)∣Y∣)2=∑iai2δi2+2∑i<jaiaj ρij δiδj.\Big(\frac{u(Y)}{\abs{Y}}\Big)^2 = \sum_i a_i^2\delta_i^2 + 2\sum_{i<j} a_i a_j\,\rho_{ij}\,\delta_i\delta_j .

Relative uncertainties add in quadrature and the exponent is squared: a denominator with 12 %12\,\% dominates numerators with 3 %3\,\% and 4 %4\,\% (you will calculate it in an exercise).

  • Second order. For normal inputs, E[Y]≈f(μ)+12tr⁡(∇2f Σ)\E[Y] \approx f(\vb{\mu}) + \tfrac{1}{2}\tr(\hess f\,\mat{\Sigma}) and Var⁡(Y)≈g⊤Σg+12tr⁡((∇2f Σ)2)\Var(Y) \approx \vb{g}\T\mat{\Sigma}\vb{g} + \tfrac{1}{2}\tr\big((\hess f\,\mat{\Sigma})^2\big). For A/BA/B with δA=10 %\delta_A = 10\,\% and δB=20 %\delta_B = 20\,\%, relative mean bias is about δB2=4 %\delta_B^2 = 4\,\% (simulation gives 4.6 %4.6\,\%) and simulated standard deviation is 27 %27\,\% of nominal value, not the linear law’s 22 %22\,\% (the second-order formula reaches 23 %23\,\%): linearization is no longer a reliable spread approximation. With δB=30 %\delta_B = 30\,\% simulated standard deviation is erratic and can exceed the linear value tens of times (one run of two million draws gave relative deviation 3030 versus 0.320.32), because the ratio of normals no longer has finite variance.

Monte Carlo propagation

If the linear law analyzes the derivative, Monte Carlo is the experiment: simulate input uncertainty and observe the output. The GUM devotes Supplement 1 (JCGM 101:2008) to it.

This is a simulation study without an unknown parameter: the input distribution is known and the output distribution is wanted. Three practical issues:

  1. How many draws. Numerical error of sample percentile q^p\hat q_p is p(1−p)/M / fY(qp)\sqrt{p(1-p)/M}\,/\,f_Y(q_p), with fYf_Y the output density at that percentile. Density is small in tails and error large: thus the guide requires MM large relative to 1/(1−p)1/(1-p), for example M≥104/(1−p)M \ge 10^4/(1-p) (two hundred thousand for p=0.95p = 0.95; it suggests M=106M = 10^6 as a starting value), or an adaptive procedure increasing MM until endpoints stabilize to the number of digits to report.
  2. Seed and reproducibility. Fix and disclose it. Runs with different seeds should agree in published digits.
  3. Validating the linear law. The recommended check compares coverage endpoints from the linear law and Monte Carlo, accepting linearization only when they agree within numerical tolerance. The figure does this with the aquamarine versus violet bars.

A propagator from scratch

We build the propagator in three pieces: gradient by centered finite differences, the linear law (with each input’s coefficient to see where uncertainty comes from), and correlated-input sampling via Cholesky factorization.

[ ]Linear propagation with finite-difference Jacobian, checked against sympyBrowser
import numpy as np
import sympy as sp

def gradiente(f, x, rel=1e-6):
    """Gradiente de f: R^p -> R por diferencias centradas, con paso relativo a cada coordenada."""
    x = np.asarray(x, float)
    g = np.zeros_like(x)
    for i in range(x.size):
        d = rel * max(abs(x[i]), 1e-3)
        xp, xm = x.copy(), x.copy()
        xp[i] += d
        xm[i] -= d
        g[i] = (f(xp) - f(xm)) / (2 * d)
    return g

def propaga_lineal(f, mu, Sigma):
    """u(Y) = sqrt(g' Sigma g); devuelve f(mu), u, el gradiente y el aporte de cada entrada a u^2 (con los cruces repartidos)."""
    mu, Sigma = np.asarray(mu, float), np.asarray(Sigma, float)
    g = gradiente(f, mu)
    aportes = g * (Sigma @ g)                       # suma de aportes = g' Sigma g
    return f(mu), np.sqrt(g @ Sigma @ g), g, aportes

# Q = A·B/C con incertidumbres relativas del 3 %, 4 % y 12 % e independientes
mu = np.array([10.0, 20.0, 5.0])
Sigma = np.diag((np.array([0.03, 0.04, 0.12]) * mu) ** 2)
Q = lambda x: x[0] * x[1] / x[2]
q0, u, g, ap = propaga_lineal(Q, mu, Sigma)
print(f"Q = {q0:.2f}, u(Q) = {u:.3f}  (relativa {100 * u / q0:.2f} %)")
print("aporte de A, B, C a u^2:", np.round(100 * ap / ap.sum(), 1), "%")

# contraste con el gradiente exacto de sympy
a, b, c = sp.symbols("a b c")
gs = sp.lambdify((a, b, c), [sp.diff(a * b / c, v) for v in (a, b, c)])
print("gradiente numérico :", np.round(g, 6))
print("gradiente de sympy :", np.round(gs(*mu), 6))

The denominator’s 12 %12\,\% contributes 85 %85\,\% of total variance (144144 of 169169 in relative-formula units): if the budget allows improving only one measurement, the choice is clear. Numerical and symbolic gradients agree in every displayed digit.

[ ]Monte Carlo with correlated inputs: Cholesky, percentiles and shortest intervalBrowser
import numpy as np

def muestrea_normal(mu, Sigma, M, rng):
    """M vectores de N(mu, Sigma) mediante la factorización de Cholesky Sigma = L L'."""
    L = np.linalg.cholesky(np.asarray(Sigma, float))
    return np.asarray(mu, float) + rng.standard_normal((M, len(mu))) @ L.T

def resumen(y, p=0.95):
    """Media, desviación típica, intervalo simétrico en probabilidad e intervalo más corto de cobertura p."""
    y = np.sort(np.asarray(y))
    M = y.size
    simetrico = np.percentile(y, [100 * (1 - p) / 2, 100 * (1 + p) / 2])
    m = int(np.ceil(p * M))
    anchos = y[m - 1:] - y[: M - m + 1]                   # todas las ventanas de m valores consecutivos
    j = int(np.argmin(anchos))
    return y.mean(), y.std(), simetrico, (y[j], y[j + m - 1])

rng = np.random.default_rng(5)
M = 400_000

# Prueba de cordura: para una función lineal con entradas normales la ley lineal es exacta.
# D = T1 - T2, u1 = 3, u2 = 4, con correlación rho entre las dos latencias.
for rho in (-0.6, 0.0, 0.6):
    Sigma = np.array([[9.0, rho * 12], [rho * 12, 16.0]])
    X = muestrea_normal([50.0, 40.0], Sigma, M, rng)
    d = X[:, 0] - X[:, 1]
    print(f"rho = {rho:+.1f}: u lineal = {np.sqrt(9 + 16 - 2 * rho * 12):.3f}, u Monte Carlo = {d.std():.3f}")

# Un caso no lineal: cociente Q = A/B con B al 25 % (normal)
X = muestrea_normal([10.0, 5.0], np.diag([1.0, 1.25 ** 2]), M, rng)
q = X[:, 0] / X[:, 1]
media, sd, sim, corto = resumen(q)
print(f"A/B: nominal 2.00, media {media:.2f}")
print(f"  intervalo simétrico en probabilidad [{sim[0]:.2f}, {sim[1]:.2f}]   (anchura {sim[1] - sim[0]:.2f})")
print(f"  intervalo más corto                [{corto[0]:.2f}, {corto[1]:.2f}]   (anchura {corto[1] - corto[0]:.2f})")
print(f"  lineal: 2.00 ± {1.96 * 2 * np.hypot(0.1, 0.25):.2f}")

With ρ=−0.6\rho = -0.6 uncertainty in the difference rises to 25+14.4=6.28\sqrt{25 + 14.4} = 6.28 and with ρ=+0.6\rho = +0.6 falls to 3.263.26: the same cancellation as clocks with shared offset. For a linear function, the linear law is exact with normal inputs, and Monte Carlo reproduces it to numerical error, a sanity check for the code. For the ratio, the shortest interval (width 2.432.43) is narrower than the probability-symmetric interval (2.742.74) because the distribution is asymmetric: with a long right tail, trim the tail and keep the dense region. Neither resembles linear interval 2±1.062 \pm 1.06, symmetric around a nominal value that is no longer the distribution center (simulated mean 2.162.16).

We still need to see how many draws are needed. Numerical error of an endpoint is p(1−p)/M/fY(qp)\sqrt{p(1-p)/M}/f_Y(q_p); the cell measures it by repeating the experiment and compares it with that formula, estimating density at percentile 97.597.5 using a large Monte Carlo run.

[ ]How many draws: numerical error of a coverage endpointBrowser
import numpy as np

rng = np.random.default_rng(11)
f = lambda a, b: a / b
mu, sd = np.array([10.0, 5.0]), np.array([1.0, 1.0])

def extremo(M):
    a = rng.normal(mu[0], sd[0], M)
    b = rng.normal(mu[1], sd[1], M)
    return np.percentile(f(a, b), 97.5)

# densidad de la salida en el percentil 97.5, a partir de un Monte Carlo grande
ref = f(rng.normal(10, 1, 2_000_000), rng.normal(5, 1, 2_000_000))
q = np.percentile(ref, 97.5)
h = 0.02
dens = np.mean(np.abs(ref - q) < h) / (2 * h)

print(f"{'M':>9s} {'desv. típica del extremo (30 repeticiones)':>46s} {'teoría':>9s}")
for M in (1_000, 10_000, 100_000):
    ex = [extremo(M) for _ in range(30)]
    teo = np.sqrt(0.975 * 0.025 / M) / dens
    print(f"{M:9d} {np.std(ex, ddof=1):46.4f} {teo:9.4f}")

Error decreases like 1/M1/\sqrt{M}, as predicted: with M=103M = 10^3 the upper endpoint’s standard deviation is almost 0.10.1 and the interval’s first decimal is already noise; with 10410^4 it drops to 0.030.03 and with 10510^5 to 0.0120.012 (the formula gives 0.0090.009; with 30 repetitions the deviation itself has relative error 13 %13\,\%, plus error in estimated density). Publishing two significant digits needs only 10510^5; the guide’s default million gives another digit of margin.

With the machinery ready, return to the motivating problem and study correlation between incident rate λ\lambda and mean cost cc (for example, both increase with service exposure). Marginals stay the same (gamma, lognormal, beta), and dependence is introduced with a Gaussian copula: draw a multivariate normal with desired correlation, pass each coordinate through Φ\Phi to obtain uniforms, and apply each marginal’s quantile function.

[ ]Expected incident cost with correlated rate and cost (Gaussian copula)Browser
import numpy as np
from scipy import stats

rng = np.random.default_rng(26)
M = 200_000
marg = [
    stats.gamma(6, scale=1 / 3),                                   # tasa de incidentes: media 2
    stats.lognorm(s=np.sqrt(np.log(1 + (18 / 85) ** 2)), scale=85 / np.sqrt(1 + (18 / 85) ** 2)),   # coste medio: media 85
    stats.beta(9.2, 13.8),                                         # fracción no eliminada: media 0.4
]

def simula(rho_lc):
    R = np.array([[1, rho_lc, 0], [rho_lc, 1, 0], [0, 0, 1.0]])
    z = rng.standard_normal((M, 3)) @ np.linalg.cholesky(R).T
    u = stats.norm.cdf(z)
    x = np.column_stack([m.ppf(u[:, i]) for i, m in enumerate(marg)])
    return x[:, 0] * x[:, 1] * x[:, 2]

print(f"{'rho(tasa, coste)':>17s} {'media':>7s} {'desv. típ.':>11s} {'intervalo al 95 %':>22s} {'P(L > 100)':>11s}")
for rho in (-0.6, 0.0, 0.6):
    L = simula(rho)
    lo, hi = np.percentile(L, [2.5, 97.5])
    print(f"{rho:17.1f} {L.mean():7.1f} {L.std():11.1f} {'[%.1f, %.1f]' % (lo, hi):>22s} {np.mean(L > 100):11.3f}")

The mean changes with correlation (from 64.764.7 to 71.571.5 k€: the product of positively correlated variables has a higher mean), standard deviation grows nearly 70 %70\,\%, from 27.427.4 to 46.046.0, and probability of exceeding 100100 k€ rises from 10.510.5 to 20.6 %20.6\,\%. Ignoring plausible correlation is not neutral: it assumes ρ=0\rho = 0, which the report should state.

Confidence, prediction and tolerance: three different questions

Given a sample x1,…,xnx_1, \dots, x_n from an assumed normal process, three intervals are constantly confused. They share center xˉ\bar x and form xˉ±c s\bar x \pm c\,s, but answer different questions.

QuestionIntervalHalf-width (normal)With n→∞n \to \infty
Where is mean μ\mu?Confidence 1−α1-\alphatn−1 s/nt_{n-1}\,s/\sqrt{n}shrinks to a point
Where will the next observation fall?Prediction 1−α1-\alphatn−1 s1+1/nt_{n-1}\,s\sqrt{1 + 1/n}tends to μ±zσ\mu \pm z\sigma
Which interval contains at least proportion β\beta of the population?Tolerance (β,γ)(\beta, \gamma)k(n,β,γ) sk(n, \beta, \gamma)\,stends to μ±z(1+β)/2σ\mu \pm z_{(1+\beta)/2}\sigma

Prediction half-width follows because Xnueva−Xˉ∼N(0,σ2(1+1/n))X_{\text{nueva}} - \bar X \sim \Normal\big(0, \sigma^2(1 + 1/n)\big) is independent of ss: the new observation contributes its own variance σ2\sigma^2 in addition to the mean’s, and the ratio with ss is tn−1t_{n-1}. Hence 1+1/n1 + 1/n: 11 never disappears however large nn becomes, because variability of one observation is irreducible.

The prediction interval averages over samples (γ\gamma is mean content); tolerance requires high content in the particular sample, with high confidence. Thus tolerance is wider, especially for small nn. For specifications such as “99 %99\,\% of requests take less than TT ms”, it is the right tool because a guaranteed threshold is requested, not one correct on average.

InteractiveConfidence, prediction and tolerance
Population, one sample and its three intervals (gray: central population interval targeted by the TI)
confidence (mean)prediction (1 observation)tolerance (95% of population)
Half-width factor cc in c sc\,s for each interval as nn grows
population quantile 1.96 σ
  • CI for mean
  • PI for an observation
  • TI (β,γ)(\beta, \gamma)
  • central population interval
10
Confidence γ\gamma (CI, PI and TI)
Population proportion β\beta to be covered by the TI
Half-width in ss units: CI | PI | TI0.72 | 2.37 | 3.38
CI coverage of the mean (1000 samples)95.4 %
Mean PI coverage of a new observation95.0 %
Samples whose TI contains at least 95 % of the population94.2 %
Population content for this sample: CI | PI | TI55.5 % | 98.9 % | 100.0 %
Confidence of [min⁡,max⁡][\min, \max] as a distribution-free tolerance interval8.6 %
With n=10n=10 the CI (half-width 0.72 s\,s) covers the mean 95.4 % of the time and barely depends on the population; the PI (2.37 s\,s) covers a new observation 95.0 %; the TI (3.38 s\,s) contains at least 95 % of the population in 94.2 % of samples. As nn grows, the CI shrinks to a point, the PI tends to ±1.96 σ\pm 1.96\,\sigma (the γ\gamma quantile), and the TI to ±1.96 σ\pm 1.96\,\sigma (the β\beta content quantile).
A standard-normal sample and the three intervals built from it. Gray shows the central population interval the tolerance interval aims to cover. At right, each interval's half-width factor cc in c sc\,s as nn grows. With n=5n=5, compare all three: tolerance is 70 % wider than prediction and four times confidence. Increase nn to 500 and check which interval shrinks to a point and which retain population width. Using 1000 repeated samples, measure what each covers: the mean, a new observation, or at least β\beta of the population.

The normal tolerance factor

For a one-sided bound there is an exact formula. Let Z=n(Xˉ−μ)/σ∼N(0,1)Z = \sqrt{n}(\bar X - \mu)/\sigma \sim \Normal(0, 1) and V=s/σV = s/\sigma, with (n−1)V2∼χn−12(n-1)V^2 \sim \chi^2_{n-1} independent of ZZ. Upper bound Xˉ+ks\bar X + k s leaves at least fraction β\beta of the population below it if and only if Xˉ+ks≥μ+zβσ\bar X + ks \ge \mu + z_\beta\sigma, equivalent to

zβn−ZV≤kn.\frac{z_\beta\sqrt{n} - Z}{V} \le k\sqrt{n}.

The left side is by definition a noncentral tt with n−1n - 1 degrees of freedom and noncentrality parameter δ=zβn\delta = z_\beta\sqrt{n} (the sign of ZZ is irrelevant because −Z∼Z-Z \sim Z). Requiring this with probability γ\gamma gives k=tn−1,γ′(δ)/nk = t'_{n-1,\gamma}(\delta)/\sqrt{n}, the γ\gamma quantile of that noncentral tt divided by n\sqrt{n}. For the two-sided interval there is no elementary exact closed form; Howe’s highly accurate approximation is

k≈z(1+β)/2(n−1)(1+1/n)χn−1; 1−γ2,k \approx z_{(1+\beta)/2}\sqrt{\frac{(n-1)(1 + 1/n)}{\chi^2_{n-1;\,1-\gamma}}},

with χn−1; 1−γ2\chi^2_{n-1;\,1-\gamma} the probability-1−γ1 - \gamma chi-square quantile. The cell below checks it by simulation.

Tolerance without distributional assumptions

Without assuming normality, interval [X(1),X(n)][X_{(1)}, X_{(n)}] formed by sample minimum and maximum is a tolerance interval with confidence that does not depend on FF.

Proof

By the probability integral transform, Ui=F(Xi)∼iidUnif⁡(0,1)U_i = F(X_i) \iid \Unif(0, 1), and since FF is increasing, C=U(n)−U(1)C = U_{(n)} - U_{(1)}, the range of nn uniforms. The joint density of minimum uu and maximum vv is n(n−1)(v−u)n−2n(n-1)(v - u)^{n-2} on 0≤u≤v≤10 \le u \le v \le 1 (choose the minimum and maximum, with the remaining n−2n-2 falling between them). With r=v−ur = v - u, the minimum can occupy any position in [0,1−r][0, 1-r], so range density is

fC(r)=∫01−rn(n−1) rn−2  ⁣du=n(n−1) rn−2(1−r),f_C(r) = \int_0^{1-r} n(n-1)\,r^{n-2}\,\dd u = n(n-1)\,r^{n-2}(1 - r),

and integrating gives distribution function P(C≤β)=nβn−1−(n−1)βn\Pr(C \le \beta) = n\beta^{n-1} - (n-1)\beta^n. Confidence is P(C≥β)=1−P(C≤β)\Pr(C \ge \beta) = 1 - \Pr(C \le \beta).

∎

This is the Beta(n−1,2)\mathrm{Beta}(n-1, 2) distribution. Read it carefully: with n=30n = 30 and β=0.95\beta = 0.95 confidence is only 45 %45\,\%, meaning the range of 3030 observations does not contain 95 %95\,\% of the population more than half the time. To have confidence 95 %95\,\% of covering 95 %95\,\% requires n=93n = 93 observations, and to cover 99 %99\,\% with the same confidence, n=473n = 473. For one-sided bounds, the maximum suffices with 1−βn≥γ1 - \beta^n \ge \gamma, that is, n≥ln⁡(1−γ)/ln⁡βn \ge \ln(1-\gamma)/\ln\beta: 5959 for β=γ=0.95\beta = \gamma = 0.95 and 299299 for percentile 9999 at confidence 95 %95\,\%. The cell below calculates and simulates this.

[ ]Tolerance intervals: Howe's normal factor, exact noncentral t bound and assumption-free [min, max]Browser
import numpy as np
from scipy import stats

def k_howe(n, beta, gamma):
    """Factor bilateral de tolerancia normal (aproximación de Howe)."""
    return stats.norm.ppf((1 + beta) / 2) * np.sqrt((n - 1) * (1 + 1 / n) / stats.chi2.ppf(1 - gamma, n - 1))

def k_unilateral(n, beta, gamma):
    """Factor exacto de la cota unilateral: cuantil gamma de la t no central con delta = z_beta sqrt(n), dividido por sqrt(n)."""
    return stats.nct.ppf(gamma, n - 1, stats.norm.ppf(beta) * np.sqrt(n)) / np.sqrt(n)

def conf_np(n, beta):
    return 1 - n * beta ** (n - 1) + (n - 1) * beta ** n

rng = np.random.default_rng(3)
beta = gamma = 0.95
print(f"{'n':>4s} {'IC':>6s} {'IP':>6s} {'IT Howe':>8s} {'IT unilateral':>14s}   (semianchuras en unidades de s)")
for n in (5, 10, 30, 100):
    t = stats.t.ppf(0.975, n - 1)
    print(f"{n:4d} {t / np.sqrt(n):6.3f} {t * np.sqrt(1 + 1 / n):6.3f} {k_howe(n, beta, gamma):8.3f} {k_unilateral(n, beta, gamma):14.3f}")

# Cobertura por simulación sobre 100 000 muestras normales
print("\nfracción de muestras cuyo IT bilateral contiene al menos el 95 % de la población:")
for n in (5, 10, 30):
    x = rng.standard_normal((100_000, n))
    m, s = x.mean(1), x.std(1, ddof=1)
    k = k_howe(n, beta, gamma)
    contenido = stats.norm.cdf(m + k * s) - stats.norm.cdf(m - k * s)
    print(f"  n = {n:3d}: {np.mean(contenido >= beta):.3f}")

# [mín, máx] sin supuestos
print("\nconfianza de [mín, máx] para beta = 0.95:", {n: round(conf_np(n, 0.95), 3) for n in (10, 30, 59, 93)})
n_min = lambda b, g: next(n for n in range(2, 5000) if conf_np(n, b) >= g)
print("n mínimo bilateral:", {(b, g): n_min(b, g) for b, g in ((0.90, 0.90), (0.95, 0.95), (0.99, 0.95))})
print("n mínimo unilateral (solo el máximo):", {(b, g): int(np.ceil(np.log(1 - g) / np.log(b))) for b, g in ((0.95, 0.95), (0.99, 0.95))})
u = rng.random((100_000, 93))
print("simulación n = 93, contenido >= 0.95:", np.mean(u.max(1) - u.min(1) >= 0.95).round(3))

The first table’s numbers tell the figure’s story: with n=10n = 10 the confidence interval has half-width 0.72 s0.72\,s, prediction 2.37 s2.37\,s, and two-sided tolerance 3.38 s3.38\,s (exact one-sided bound 2.91 s2.91\,s). As nn grows, the first shrinks to 00, and the other two converge to the same limit, 1.96 s1.96\,s when β=0.95\beta = 0.95, but tolerance approaches from above: at n=100n = 100 it still measures 2.23 s2.23\,s, the price of not knowing σ\sigma.

Combining evidence: inverse-variance weighting

The same effect is measured repeatedly in different studies, evaluation sets or facilities, and each measurement θ^i\hat\theta_i comes with standard error sis_i. How should they be combined? A simple average treats precise and noisy measurements equally. The module’s criterion (minimum variance among unbiased linear estimators) gives the answer.

Proof

By the Cauchy–Schwarz inequality,

1=(∑iai)2=(∑i(aivi)1vi)2≤(∑iai2vi)(∑i1vi),1 = \Big(\sum_i a_i\Big)^2 = \Big(\sum_i (a_i\sqrt{v_i})\frac{1}{\sqrt{v_i}}\Big)^2 \le \Big(\sum_i a_i^2 v_i\Big)\Big(\sum_i \frac{1}{v_i}\Big),

so Var⁡(T)≥1/∑iwi\Var(T) \ge 1/\sum_i w_i. Equality holds exactly when vectors (aivi)i(a_i\sqrt{v_i})_i and (1/vi)i(1/\sqrt{v_i})_i are proportional, that is, ai∝1/via_i \propto 1/v_i, and constraint ∑ai=1\sum a_i = 1 fixes the constant.

∎

This is the Gauss–Markov theorem for kk observations with common mean and diagonal covariance; if estimates were correlated with covariance V\mat{V}, the optimum would be V−11/(1⊤V−11)\mat{V}\inv\vb{1}/(\vb{1}\T\mat{V}\inv\vb{1}) with variance 1/(1⊤V−11)1/(\vb{1}\T\mat{V}\inv\vb{1}). The result depends on a strong assumption: all θ^i\hat\theta_i estimate the same θ\theta. If each study estimates its own effect, the variance of θ^EF\hat\theta_{\text{EF}} is minimal for the wrong target, and the interval from 1/∑wi1/\sum w_i is too narrow.

Heterogeneity: when studies estimate different things

The first question is whether data are compatible with one θ\theta. Once θ^EF\hat\theta_{\text{EF}} is calculated, Cochran’s QQ statistic measures weighted discrepancy,

Q=∑iwi (θ^i−θ^EF)2,Q = \sum_i w_i\,(\hat\theta_i - \hat\theta_{\text{EF}})^2 ,

which under homogeneity and normality follows χk−12\chi^2_{k-1} (one degree of freedom is lost estimating θ\theta). To measure how much heterogeneity there is, use

I2=max⁡(0,Q−(k−1)Q),I^2 = \max\Big(0, \frac{Q - (k - 1)}{Q}\Big),

the fraction of variation in QQ exceeding what chance predicts (E[Q]=k−1\E[Q] = k - 1 without heterogeneity). It is a ratio, not a size: I2=0.75I^2 = 0.75 describes not how far apart studies are but what fraction of observed variation is not sampling noise.

Proof

Expand Q=∑iwiθ^i2−(∑iwiθ^i)2/∑iwiQ = \sum_i w_i\hat\theta_i^2 - (\sum_i w_i\hat\theta_i)^2/\sum_i w_i. With E[θ^i2]=vi+τ2+θ2\E[\hat\theta_i^2] = v_i + \tau^2 + \theta^2 and wivi=1w_i v_i = 1, the first term has expectation k+τ2∑wi+θ2∑wik + \tau^2\sum w_i + \theta^2\sum w_i. For the second, Var⁡(∑wiθ^i)=∑wi2(vi+τ2)=∑wi+τ2∑wi2\Var(\sum w_i\hat\theta_i) = \sum w_i^2(v_i + \tau^2) = \sum w_i + \tau^2\sum w_i^2 and the squared mean is θ2(∑wi)2\theta^2(\sum w_i)^2, so its expectation divided by ∑wi\sum w_i is 1+τ2∑wi2/∑wi+θ2∑wi1 + \tau^2\sum w_i^2/\sum w_i + \theta^2\sum w_i. Subtracting cancels θ2\theta^2 and gives the result. Equating QQ to its expectation and solving for τ2\tau^2 (truncating at 00) gives τ^2\hat\tau^2.

∎

See what τ2\tau^2 does to the weights: wi∗=1/(vi+τ2)w_i^* = 1/(v_i + \tau^2). If τ2\tau^2 is large relative to viv_i, all weights become equal, because between-study uncertainty is common to all and individual precision no longer discriminates. A single enormous study no longer dominates. Try it.

InteractiveInteractive forest plot
Estimates from kk studies (or seeds), their 95% intervals and both pooled estimates
−101234effect (metric improvement in points)estimate [95% CI]weight FE | REStudy 11.10 [0.22, 1.98]15 % | 17 %Study 20.30 [−0.48, 1.08]19 % | 19 %Study 31.80 [0.72, 2.88]10 % | 13 %Study 40.70 [0.11, 1.29]34 % | 25 %Study 51.40 [0.42, 2.38]12 % | 15 %Study 60.00 [−1.18, 1.18]9 % | 12 %Fixed effectRandom effectsPrediction0.82 [0.48, 1.17]0.86 [0.39, 1.33][−0.38, 2.10]no effect
  • study (square: estimate; circle: CI endpoint)
  • fixed effect
  • random effects
  • prediction interval
1.10
0.45
Square sizes use weights from
Fixed effect: estimate | SE0.82 | 0.18
Fixed effect: 95% CI[0.48, 1.17]
Random effects: estimate | SE0.86 | 0.24
Random effects: 95% CI[0.39, 1.33]
Cochran QQ (5 df) | pp-value8.63 | 0.125
I2I^2 | τ^2\hat\tau^2 (DerSimonian-Laird)42 % | 0.142
Study 1 weight: fixed | random effects15 % | 17 %
Prediction interval for a new study[−0.38, 2.10]
Moderate heterogeneity (I2I^2 = 42 %). Random effects has standard error 0.24 versus 0.18 for fixed effect: 1.37 times wider, reflecting that studies estimate different effects.
Six studies (for example, improvement of one method over another on six evaluation sets) with 95 % intervals. Drag the squares and interval endpoints, or use the selected study's sliders. Below, the orange diamond is the fixed effect and magenta the random effect, with prediction for a new study. Press “Add large discrepant study”: the fixed effect jumps toward the new study, which takes about two thirds of weight, while the random effect moves much less because τ^2\hat\tau^2 grows and weights spread out. With the original six studies move one left and watch I2I^2 rise from moderate to high.

With initial values, Q=8.6Q = 8.6 with 55 degrees of freedom (p=0.12p = 0.12), I2=42 %I^2 = 42\,\% and τ^2=0.14\hat\tau^2 = 0.14. Fixed and random effects give nearly the same central value (0.820.82 and 0.860.86), but random-effects standard error is 0.240.24 versus 0.180.18: its interval is 37 %37\,\% wider, reflecting that the six estimates differ more than their noise explains. Adding the large study (effect 2.62.6, standard error 0.120.12) sends the fixed effect to 2.032.03 with interval only ±0.19\pm 0.19, pulled by a study carrying 68 %68\,\% of weight, while random effects remain at 1.161.16 with ±0.93\pm 0.93 (the new study falls to 16 %16\,\% of weight): this honestly reflects uncertainty about which of the seven is “true”. The initial six studies’ prediction interval, [−0.38,2.10][-0.38, 2.10], already warned us: mean effect is clearly positive (interval [0.39,1.33][0.39, 1.33]), but a seventh evaluation set could yield zero or negative improvement. In practice, when studies disagree, fixed effect gives a narrow, falsely confident interval.

Meta-analysis from scratch

The cell calculates all of the above for the six studies in the figure, draws the forest plot and repeats after adding the discrepant study.

[ ]Meta-analysis from scratch: fixed effect, DerSimonian–Laird, I² and forest plotBrowser
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

def meta(y, se):
    """Efecto fijo y de efectos aleatorios (DerSimonian-Laird), Q, I², tau² e intervalo de predicción."""
    y, v = np.asarray(y, float), np.asarray(se, float) ** 2
    k = len(y)
    w = 1 / v
    fe = np.sum(w * y) / w.sum()
    Q = np.sum(w * (y - fe) ** 2)
    tau2 = max(0.0, (Q - (k - 1)) / (w.sum() - np.sum(w ** 2) / w.sum()))
    ws = 1 / (v + tau2)
    re = np.sum(ws * y) / ws.sum()
    se_re = ws.sum() ** -0.5
    pred = None
    if k >= 3:
        r = stats.t.ppf(0.975, k - 2) * np.sqrt(tau2 + se_re ** 2)
        pred = (re - r, re + r)
    return dict(fe=fe, se_fe=w.sum() ** -0.5, re=re, se_re=se_re, Q=Q, p_Q=stats.chi2.sf(Q, k - 1),
                I2=max(0.0, (Q - (k - 1)) / Q), tau2=tau2, w_fe=w / w.sum(), w_re=ws / ws.sum(), pred=pred)

y = np.array([1.1, 0.3, 1.8, 0.7, 1.4, 0.0])
se = np.array([0.45, 0.40, 0.55, 0.30, 0.50, 0.60])
r = meta(y, se)
print(f"efecto fijo        {r['fe']:.3f} ± {1.96 * r['se_fe']:.3f}")
print(f"efectos aleatorios {r['re']:.3f} ± {1.96 * r['se_re']:.3f}")
print(f"Q = {r['Q']:.2f} (p = {r['p_Q']:.3f}), I² = {100 * r['I2']:.0f} %, tau² = {r['tau2']:.3f}")
print(f"intervalo de predicción de un estudio nuevo: [{r['pred'][0]:.2f}, {r['pred'][1]:.2f}]")

r2 = meta(np.append(y, 2.6), np.append(se, 0.12))
print(f"\ncon el estudio grande y discrepante (2.6, 0.12):")
print(f"efecto fijo        {r2['fe']:.3f} ± {1.96 * r2['se_fe']:.3f}")
print(f"efectos aleatorios {r2['re']:.3f} ± {1.96 * r2['se_re']:.3f}   (peso relativo del nuevo estudio: {100 * r2['w_fe'][-1]:.0f} % en EF, {100 * r2['w_re'][-1]:.0f} % en EA)")
print(f"I² = {100 * r2['I2']:.0f} %, tau² = {r2['tau2']:.3f}")

fig, ax = plt.subplots(figsize=(7.2, 3.8))
n = len(y)
for i in range(n):
    ax.plot([y[i] - 1.96 * se[i], y[i] + 1.96 * se[i]], [n - i] * 2, color="C0", lw=1.8)
    ax.plot(y[i], n - i, "s", color="C0", ms=4 + 18 * r["w_fe"][i])
for yy, (m, s, col, nom) in zip((0, -1), ((r["fe"], r["se_fe"], "C1", "efecto fijo"), (r["re"], r["se_re"], "C4", "efectos aleatorios"))):
    ax.fill([m - 1.96 * s, m, m + 1.96 * s, m], [yy, yy + 0.3, yy, yy - 0.3], color=col, label=nom)
ax.plot(r["pred"], [-1.8, -1.8], color="C4", ls="--", lw=2, label="predicción")
ax.axvline(0, color="gray", lw=1)
ax.set_yticks(list(range(n, 0, -1)) + [0, -1, -1.8], [f"estudio {i + 1}" for i in range(n)] + ["efecto fijo", "ef. aleatorios", "predicción"])
ax.set_xlabel("efecto (puntos)")
ax.legend(loc="lower right", fontsize=8)
plt.show()

With the discrepant study, study 77 carries 68 %68\,\% of fixed-effect weight and only 16 %16\,\% under random effects, while I2I^2 rises from 4242 to 92 %92\,\%. Why does I2I^2 rise so much? Because the new study is very precise (s=0.12s = 0.12), and with small measurement errors almost all observed variation is heterogeneity. Thus I2I^2 does not measure distance between effects, but how much observed variation is not noise; τ^\hat\tau measures the former.

With few studies (small kk), DerSimonian–Laird τ^2\hat\tau^2 is downward biased and normal intervals are too short. Common alternatives are the Hartung–Knapp–Sidik–Jonkman correction, using tk−1t_{k-1} and a standard error rescaled by observed heterogeneity, and τ2\tau^2 estimators such as REML or Paule–Mandel. The statsmodels function in the libraries section offers Paule–Mandel (method_re="iterated") and Hartung–Knapp; REML requires fitting the random-effects model by restricted maximum likelihood using other tools. The QQ test also has little power for small kk: large pp does not prove homogeneity.

Communicating uncertainty

Analysis ends when someone else reads the result and makes a decision with it. Much uncertainty is lost, or invented, at that final stage.

Three bars that mean different things

The same bar around a mean can represent three things, and the reader cannot guess which.

  • Standard deviation ss: describes data spread. It does not shrink with nn.
  • Standard error s/ns/\sqrt{n}: precision of the mean. It is smaller by factor n\sqrt{n}, so many figures prefer it, but coverage is low: xˉ±1 EE\bar x \pm 1\,\mathrm{EE} is a confidence interval of level 68 %68\,\% for large nn and only 58 %58\,\% for n=3n = 3.
  • 95 %95\,\% confidence interval: xˉ±tn−1 EE\bar x \pm t_{n-1}\,\mathrm{EE}, with tn−1≈2t_{n-1} \approx 2 for large nn and 4.304.30 for n=3n = 3.

The most common reading is “if bars overlap, there is no difference”. This is false. For two independent groups with standard errors e1e_1 and e2e_2, the difference test is significant when ∣d∣>ze12+e22\abs{d} > z\sqrt{e_1^2 + e_2^2} (with z=1.96z = 1.96 for α=0.05\alpha = 0.05 and large nn), whereas 95 %95\,\% intervals stop overlapping when ∣d∣>z(e1+e2)\abs{d} > z(e_1 + e_2). Since e12+e22≤e1+e2\sqrt{e_1^2 + e_2^2} \le e_1 + e_2, separation implies significance, but not conversely. With equal standard errors ee, the test requires ∣d∣>2.77e\abs{d} > 2.77e and intervals separate only at ∣d∣>3.92e\abs{d} > 3.92e: between 2.77e2.77e and 3.92e3.92e the difference is significant while intervals overlap, up to 59 %59\,\% of each interval’s half-width. Standard-error bars behave oppositely: they stop overlapping at ∣d∣>2e\abs{d} > 2e, before significance; a gap does not imply p<0.05p < 0.05.

InteractiveWhat error bars do and do not say
Two groups with 95% CI bars
group 1group 2
When bars separate versus when the difference is significant (scale: ∣d∣|d| in standard errors of dd)
SDSE95% CIp < 0.05 from 2.050123456|d| / standard error of d
  • bars of this type overlap up to here
  • visual–test disagreement region
  • significance threshold (p < 0.05 to its right)
  • your difference
What the bars show
15
2.5
2.5
Difference d=m2−m1d = m_2 - m_1 | standard error of dd2.00 | 0.91
Welch tt statistic | degrees of freedom2.19 | 28.0
Two-sided pp-value0.037
Overlap? SD | SE | 95% CIyes | no | yes
Bars separate at ∣d∣|d| ≥2.77 (3.03 standard errors of d)
Significant despite overlapping bars. ∣t∣=2.19|t| = 2.19 and p=0.037p = 0.037, but 95% CI bars overlap. Overlap does not imply nonsignificance.
Two groups with draggable means (large points) and your chosen bars. At right, the same difference in standard errors of the difference: the dashed line marks p<0.05p < 0.05, and each row marks how far bars of that kind overlap. Red is where visual reading and the test conflict. With initial values, 95 % intervals overlap and the test is significant. Switch to standard error and standard deviation without changing data: the image changes completely and the test does not. Then drag a mean until the test crosses p=0.05p = 0.05 and note when each type of bar separates.

Simulation measures the cost of using overlap as a test: with no real difference, how often would each rule declare a “difference”?

[ ]Overlap as a test: false-positive rate with no differenceBrowser
import numpy as np
from scipy import stats

rng = np.random.default_rng(14)
R, n, s = 200_000, 15, 1.0
a = rng.normal(0, s, (R, n))
b = rng.normal(0, s, (R, n))                       # misma población: toda «diferencia» es un falso positivo
ma, mb = a.mean(1), b.mean(1)
sa, sb = a.std(1, ddof=1), b.std(1, ddof=1)
ea, eb = sa / np.sqrt(n), sb / np.sqrt(n)
d = np.abs(ma - mb)
t = stats.t.ppf(0.975, n - 1)

welch = d / np.hypot(ea, eb)
df = np.hypot(ea, eb) ** 4 / (ea ** 4 / (n - 1) + eb ** 4 / (n - 1))
p = 2 * stats.t.sf(welch, df)

print(f"test de Welch con p < 0.05:                       {np.mean(p < 0.05):.4f}")
print(f"IC 95 % que NO se solapan (regla visual):         {np.mean(d > t * (ea + eb)):.4f}")
print(f"barras de error estándar que NO se solapan:       {np.mean(d > ea + eb):.4f}")
print(f"barras de desviación típica que NO se solapan:    {np.mean(d > sa + sb):.4f}")

The asymmetry is striking. Checking whether 95 %95\,\% intervals overlap almost never declares differences (≈0.6 %\approx 0.6\,\% false positives): it protects against type-I error so strongly that it loses power and misses real differences. Checking whether standard-error bars separate instead has 17 %17\,\% false positives. Standard-deviation bars never separate by chance, because they describe data rather than precision. The practical rule from Cumming and Krzywinski and Altman: with 95 %95\,\% intervals from two independent groups of similar size, overlap of up to half a half-width remains compatible with p≈0.05p \approx 0.05; use the test (or better, the difference interval), not the eye, for comparison.

Significant figures and notation

Giving more digits than uncertainty justifies communicates something false: 12.3456±0.067812.3456 \pm 0.0678 suggests precision contradicted by its second term. GUM (§7.2.6) and Particle Data Group convention is to round uncertainty first, to one or two significant figures, then the estimate to the same decimal place. The PDG rule chooses one or two figures based on the first three digits of uu: 100100 through 354354, two; 355355 through 949949, one; 950950 through 999999, round to 10001000 and retain two. The cell implements edge cases and compact notation 12.35(7)12.35(7), with uncertainty in the last digits in parentheses.

[ ]Rounding a result to its uncertainty (PDG rule) and compact notationBrowser
import numpy as np
from decimal import Decimal, ROUND_HALF_EVEN

def redondea(x, u):
    """Devuelve (x, u) redondeados con la regla del PDG: u con 1 o 2 cifras significativas, x en el mismo lugar decimal."""
    if u <= 0:
        raise ValueError("la incertidumbre debe ser positiva")
    e = int(np.floor(np.log10(u)))                      # u = m · 10^e con 1 <= m < 10
    tres = int(round(u / 10 ** (e - 2)))                # tres primeras cifras (100..999) o 1000 tras redondear
    if tres >= 950:                                     # 950..999 sube a 1.0 · 10^(e+1), con dos cifras
        e += 1
        cifras = 2
    elif tres >= 355:
        cifras = 1
    else:
        cifras = 2
    lugar = e - (cifras - 1)                            # exponente del último decimal que se conserva
    q = Decimal(1).scaleb(lugar)
    ur = Decimal(repr(u)).quantize(q, rounding=ROUND_HALF_EVEN)
    xr = Decimal(repr(x)).quantize(q, rounding=ROUND_HALF_EVEN)
    return xr, ur, lugar

def formato(x, u):
    xr, ur, lugar = redondea(x, u)
    mant = int(ur.scaleb(-lugar))                       # incertidumbre como entero en el último lugar
    if lugar < 0:
        return f"{xr:f}({mant})"
    return f"{xr:f} ± {ur:f}"

casos = [(12.3456, 0.0678), (12.3456, 0.0123), (12.3456, 0.0996), (1234.5678, 56.78), (0.0012345, 0.0000456), (25.40, 0.2088)]
for x, u in casos:
    xr, ur, _ = redondea(x, u)
    print(f"{x!r:>10} ± {u!r:<10}  ->  {xr:f} ± {ur:f}      compacto: {formato(x, u)}")

Consider 0.09960.0996: its first three digits, 996996, fall between 950950 and 999999, uncertainty rounds up to 0.100.10 and two digits are retained, so the result is 12.35±0.1012.35 \pm 0.10, or 12.35(10)12.35(10). With one digit one would publish 12.3±0.112.3 \pm 0.1, and rounding the estimate to tenths could shift it by up to 0.050.05, half the uncertainty itself. Also compare 0.06780.0678, which takes one digit (0.070.07), with 0.01230.0123, which takes two (0.0120.012): with only one, 0.010.01, almost 20 %20\,\% of uncertainty would be lost. Two cautions: do not round intermediate results, only the published one; and give numbers used in later calculations one extra digit.

How to plot

  • Show the data if few. With n<30n < 30 per group, individual points say more than any bar; a bar chart with error bars (“dynamite”) hides distribution, sample size and outliers.
  • Label the bar in the figure. “Mean ± standard error, n=15n = 15 users per group”, or “95 %95\,\% CI (percentile bootstrap, 10410^4 resamples)”. Without a label the figure cannot be interpreted.
  • Show the difference with its interval, not two separate intervals. It is the reader’s question and the one the test answers.
  • Interval plots. One row per estimate and interval, ordered with the reference (zero, a threshold) visible: the preceding forest plot is the model. Better than a table of pp values.
  • Honest scale. An estimate-plot axis need not start at zero, but a bar-chart axis should; draw the same quantity on the same scale across compared panels.

Checklist for an honest statistical report

  1. Estimate and interval together. Every number includes uncertainty, with level (95 %95\,\%) and type (confidence, prediction, tolerance, standard error).
  2. The question determines the interval. Is it about a parameter, the next observation or a compliance threshold? See the interval table.
  3. Analysis unit and independence. What is an observation? Are there repeated measures, seeds on the same test set, users with multiple sessions? If dependent, naive standard error is too small.
  4. Assumptions and checks. Distribution, linearization, homogeneity. If linearized, was it compared with Monte Carlo? If studies were combined, is there heterogeneity (QQ, I2I^2, τ^\hat\tau), and was the appropriate model used?
  5. Correlations. Are propagated inputs independent? If assumed, say so.
  6. Included and excluded sources. Explicitly list what the figure includes (sampling, instrument) and excludes (model, data drift, selection bias). Unquantified uncertainty does not disappear when omitted.
  7. Sensitivity. Does the conclusion change under less certain assumptions? A table of intervals under each alternative is more honest than one interval.
  8. Effect size, not only pp. A small pp value with trivial effect and a large pp with an interval including important effects are very different results (effect size).
  9. Multiplicity. If many comparisons were examined, was this corrected or disclosed (multiple comparisons)?
  10. Digits and reproducibility. Rounding consistent with uncertainty, seed, code version and data version.

With libraries: statsmodels, scipy and quasi-Monte Carlo

statsmodels.stats.meta_analysis.combine_effects performs meta-analysis with several τ2\tau^2 estimators and Hartung–Knapp correction. scipy.stats.qmc provides Sobol sequences, covering input space more uniformly than pseudorandom numbers and reducing propagation’s numerical error for smooth models. The cell compares both with the implementations above.

[ ]combine_effects versus the homemade implementation, and Sobol versus ordinary Monte CarloBrowser
import numpy as np
from scipy import stats
from scipy.stats import qmc
from statsmodels.stats.meta_analysis import combine_effects

y = np.array([1.1, 0.3, 1.8, 0.7, 1.4, 0.0])
se = np.array([0.45, 0.40, 0.55, 0.30, 0.50, 0.60])
res = combine_effects(y, se ** 2, method_re="chi2")        # "chi2" es el estimador de DerSimonian-Laird
tabla = res.summary_frame()
print(tabla.loc[["fixed effect", "random effect", "random effect wls"], ["eff", "sd_eff", "ci_low", "ci_upp"]].round(3))
print(f"tau² = {res.tau2:.3f}, Q = {res.q:.2f}, I² = {100 * res.i2:.0f} %")
print("la fila «wls» es la corrección de Hartung-Knapp: error estándar", round(float(tabla.loc["random effect wls", "sd_eff"]), 3), "frente a", round(float(tabla.loc["random effect", "sd_eff"]), 3))

# Propagación del coste esperado con M = 2^13 sorteos: Monte Carlo ordinario frente a Sobol aleatorizado
marg = [stats.gamma(6, scale=1 / 3),
        stats.lognorm(s=np.sqrt(np.log(1 + (18 / 85) ** 2)), scale=85 / np.sqrt(1 + (18 / 85) ** 2)),
        stats.beta(9.2, 13.8)]
def coste(u):
    return np.prod([m.ppf(np.clip(u[:, i], 1e-12, 1 - 1e-12)) for i, m in enumerate(marg)], axis=0)

rng = np.random.default_rng(8)
ests_mc, ests_qmc = [], []
for rep in range(25):
    ests_mc.append(coste(rng.random((2 ** 13, 3))).mean())
    ests_qmc.append(coste(qmc.Sobol(3, scramble=True, seed=rep).random(2 ** 13)).mean())
print(f"\nmedia del coste con 8192 sorteos, 25 repeticiones (valor exacto 68.0):")
print(f"  Monte Carlo ordinario: desviación típica entre repeticiones {np.std(ests_mc, ddof=1):.3f}")
print(f"  Sobol aleatorizado:    desviación típica entre repeticiones {np.std(ests_qmc, ddof=1):.3f}")

The statsmodels table reproduces the homemade implementation’s numbers (0.8230.823, 0.8560.856, τ^2=0.142\hat\tau^2 = 0.142) and adds the Hartung–Knapp row, with slightly greater standard error. Quasi-Monte Carlo reduces numerical error of the mean from 0.440.44 to 0.0020.002 with the same number of evaluations, because the integrand is a product of monotone functions of one input each (low effective dimension) and Sobol projections onto each coordinate are perfectly stratified. For discontinuous models, strong interactions among many inputs, or extreme percentiles, the advantage diminishes, so GUM relies on ordinary Monte Carlo and its error analysis.

Common mistakes

Exercises

NumericRelative uncertainty of a ratio
Calculate Q=A B/CQ = A\,B/C using three independent quantities with relative uncertainties 3 %3\,\%, 4 %4\,\% and 12 %12\,\% respectively. What is the relative uncertainty of QQ, as a percentage?
NumericCombining two estimates
Two independent studies estimate the same quantity: the first gives 1010 with standard error 22, the second 1414 with standard error 44. What is the inverse-variance weighted combined estimate?
NumericDifference between latencies measured with one clock
Two latencies T1T_1 and T2T_2, measured with the same clock, have standard uncertainties 33 ms and 44 ms and correlation ρ=0.6\rho = 0.6. What is the standard uncertainty of difference T1−T2T_1 - T_2 in ms?
NumericThe I² statistic for three studies
Three studies with the same standard error 11 give estimates 00, 22 and 44. What is I2I^2 as a percentage?
ProofInverse-variance weighting is optimal
Prove: Let θ^1,…,θ^k\hat\theta_1, \dots, \hat\theta_k be independent, with E[θ^i]=θ\E[\hat\theta_i] = \theta and Var⁡(θ^i)=vi\Var(\hat\theta_i) = v_i. Prove that among estimators T=∑iaiθ^iT = \sum_i a_i\hat\theta_i unbiased for any θ\theta, the minimum-variance estimator has ai∝1/via_i \propto 1/v_i, and calculate its variance.
0
Solve using Lagrange multipliers, a different route from the Cauchy–Schwarz inequality used in the text.

Step 1 of 5. Which optimization problem must be solved?

Code[min, max] confidence and minimum sample size
Implement confianza_np(n, beta), the confidence with which interval [X(1),X(n)][X_{(1)}, X_{(n)}] of a sample of size nn from a continuous distribution contains at least proportion β\beta of the population, and n_minimo(beta, gamma), the smallest nn for which that confidence is at least γ\gamma. Hint: content is Beta(n−1,2)\mathrm{Beta}(n-1, 2).
import numpy as np

def confianza_np(n, beta):
  """Confianza de que [min, max] contenga al menos una proporcion beta de la poblacion."""
  # tu código
  return None

def n_minimo(beta, gamma):
  """Menor n con confianza_np(n, beta) >= gamma."""
  # tu código
  return None
Shift+Enter to run
QuizConfidence, prediction or tolerance
Forty approximately normal service latencies have been measured. Three questions: (1) what is the service's mean latency? (2) what latency will the next request have? (3) what threshold TT guarantees, with high confidence, that 99 %99\,\% of requests take less than TT? Which interval answers each, in order?
QuizOverlapping bars
Two independent groups with n=20n = 20 and similar standard deviations are plotted with 95 % confidence interval bars. Bars overlap slightly and Welch's tt test gives p=0.03p = 0.03. What is correct?
QuizA large discrepant study
Six moderately heterogeneous studies are combined. A seventh, very large study (small standard error) is added, with an effect much larger than the rest. What happens?

Summary

Key idea

Uncertainty is propagated (linear law u2=g⊤Σgu^2 = \vb{g}\T\mat{\Sigma}\vb{g}, exact to first order and poor near singularities; Monte Carlo when linearization fails, with M≥104/(1−p)M \ge 10^4/(1-p) draws and percentiles as coverage interval), chosen to match the question (confidence for a parameter, prediction for an observation, tolerance for a guaranteed population proportion, 1−nβn−1+(n−1)βn1 - n\beta^{n-1} + (n-1)\beta^n for [min⁡,max⁡][\min, \max]), combined (inverse-variance weighting is the optimal unbiased linear estimator if all estimate the same thing; otherwise random effects with τ^2=(Q−(k−1))/(∑w−∑w2/∑w)\hat\tau^2 = (Q - (k-1))/(\sum w - \sum w^2/\sum w)), and communicated with label, analysis unit, data and unquantified sources. As a difference grows, standard-error bars stop overlapping before the test is significant, and 95 %95\,\% intervals afterward.

Next in the module: post-selection inference and inference with ML predictions studies what happens to these intervals when data were previously used to choose what to analyze or some labels are model predictions.