Algorithm Search⌘K

Algorithmintro

Student t confidence interval

Also called t interval for a mean.

The interval x-bar plus or minus t_(n-1, 1-alpha/2) S/sqrt(n) for a normal mean with unknown variance. Exact coverage 1 - alpha under normal iid data; asymptotic otherwise. O(n).

Time
Θ(n) worst · best
Space
Θ(1) extra
Where
n = the number of observations
Properties
deterministicexactofflineiterative
Origin
William Sealy Gosset, Jerzy Neyman, 1937

The Student t confidence interval for the mean μ\mu of a normal population with unknown standard deviation is Xˉ±t(n−1,1−α/2)S/n\bar X \pm t_{(n-1, 1-\alpha/2)}S/\sqrt n, where S2S^2 is the sample variance with divisor n−1n - 1 and t(n−1,p)t_{(n-1, p)} is the lower pp quantile of the t distribution with n−1n - 1 degrees of freedom. Under iid normal data its confidence coverage is exactly 1−α1 - \alpha for every μ\mu, σ\sigma and n≥2n \ge 2: it is built from a pivot whose law is free of both parameters. It is the set of null values that the two-sided Student t-test does not reject, an instance of test-interval duality. Without normality the coverage is only asymptotic.

In plain words

You want a range of plausible values for a true average, from a few measurements, without knowing how much single measurements scatter. Take the sample average, estimate its typical error from the same data, and go a fixed number of typical errors to each side. The number comes from Student's law of the standardized average, so it is larger than the familiar 1.96 when there are few measurements: about 2.78 with five values and 12.7 with two. If the data come from a bell curve, the procedure catches the true average in 95 of every 100 samples in the long run. Any single computed range either contains the true average or does not; the 95 describes the method, not that range.

The problem

Model. X1,…,XnX_1, \dots, X_n iid N(μ,σ2)N(\mu, \sigma^2) with μ\mu and σ\sigma unknown, n≥2n \ge 2, and a confidence level 1−α∈(0,1)1 - \alpha \in (0, 1). Find a random interval [L,U][L, U], a function of the data only, with Pμ,σ(L≤μ≤U)≥1−αP_{\mu,\sigma}(L \le \mu \le U) \ge 1 - \alpha for all (μ,σ)(\mu, \sigma), as short as possible.

Pivot. Q=(Xˉ−μ)/(S/n)Q = (\bar X - \mu)/(S/\sqrt n) has the tn−1t_{n-1} law for every μ\mu and σ\sigma.

Interval. Two-sided: Xˉ±t(n−1,1−α/2)S/n\bar X \pm t_{(n-1, 1-\alpha/2)}S/\sqrt n. Lower confidence bound: [Xˉ−t(n−1,1−α)S/n,∞)[\bar X - t_{(n-1, 1-\alpha)}S/\sqrt n, \infty). Upper confidence bound: (−∞,Xˉ+t(n−1,1−α)S/n](-\infty, \bar X + t_{(n-1, 1-\alpha)}S/\sqrt n].

Coverage type. Exact: under the model the coverage equals 1−α1 - \alpha at every parameter value, not only as an infimum. The probability is marginal, over repeated samples. Outside normality, for iid data with finite variance, the coverage tends to 1−α1 - \alpha as n→∞n \to \infty by the central limit theorem and Slutsky's theorem; it is then asymptotic, and not uniformly so.

Duality. μ0\mu_0 lies in the open interval exactly when the two-sided level-α\alpha t-test of H0:μ=μ0H_0: \mu = \mu_0 does not reject, that is when its p-value exceeds α\alpha; at the two end points the p-value equals α\alpha.

The algorithm

  1. T-INTERVAL(x[1..n], 1 − α, side) ▷ n ≥ 2
  2. 1n ← the length of x
  3. 2x̄ ← (x[1] + ... + x[n]) / n
  4. 3S² ← ((x[1] − x̄)² + ... + (x[n] − x̄)²) / (n − 1) ▷ second pass, divisor n − 1
  5. 4se ← √(S² / n)
  6. 5if side = two-sided then q ← t_(n−1, 1−α/2)
  7. 6return [x̄ − q · se, x̄ + q · se]
  8. 7q ← t_(n−1, 1−α)
  9. 8if side = lower then return [x̄ − q · se, ∞)
  10. 9return (−∞, x̄ + q · se]

The quantile is found by bisection on the upper tail Fˉn−1(x)=P(Tn−1>x)\bar F_{n-1}(x) = P(T_{n-1} > x), which the helper evaluates by the continued fraction of the regularized incomplete beta function: Fˉν(x)=12Iν/(ν+x2)(ν/2,1/2)\bar F_\nu(x) = \tfrac12 I_{\nu/(\nu + x^2)}(\nu/2, 1/2) for x≥0x \ge 0. Bisecting on the upper tail, not on 1−F1 - F, keeps the digits of small tail probabilities. The code caches the quantile for each (p,n−1)(p, n - 1), which matters when the interval is computed many times, as in a simulation. If all values are equal, S=0S = 0 and the interval is the single point xˉ\bar x; this happens with probability 0 under the model.

Example

The paired sleep data of Cushny and Peebles, used by Student in 1908: the extra hours of sleep under drug 2 minus drug 1 for 10 patients are 1.2,2.4,1.3,1.3,0.0,1.0,1.8,0.8,4.6,1.41.2, 2.4, 1.3, 1.3, 0.0, 1.0, 1.8, 0.8, 4.6, 1.4. A 95% interval for the mean difference:

line value
L2: dˉ=15.8/10\bar d = 15.8/10 1.581.58
L3: S2=13.616/9S^2 = 13.616/9 1.5128891.512889
L4: se=1.512889/10se = \sqrt{1.512889/10} 0.3889590.388959
L5: q=t(9,0.975)q = t_{(9, 0.975)} 2.2621572.262157
L6: 1.58∓2.262157×0.3889591.58 \mp 2.262157 \times 0.388959 [0.7001,2.4599][0.7001, 2.4599]

The interval excludes 0, matching the t-test p-value of 0.0028. The 99% interval, with t(9,0.995)=3.249836t_{(9, 0.995)} = 3.249836, is [0.3159,2.8441][0.3159, 2.8441], and the 95% lower bound, with t(9,0.95)=1.833113t_{(9, 0.95)} = 1.833113, is 0.86700.8670. Using 1.96 in place of 2.262157 would give [0.8176,2.3424][0.8176, 2.3424], which is too short.

Coverage. Monte Carlo with r=20000r = 20000 replications of nominal 95% intervals (standard error of an estimated coverage near 0.95: 0.0015):

data nn two-sided lower bound upper bound seed
normal, μ=4\mu = 4, σ=2\sigma = 2 2 0.9507 31
normal, μ=4\mu = 4, σ=2\sigma = 2 5 0.9530 31
normal, μ=4\mu = 4, σ=2\sigma = 2 20 0.9496 31
exponential, mean 1 5 0.8802 0.9891 0.8423 32
exponential, mean 1 30 0.9273 0.9776 0.9023 32
exponential, mean 1 100 0.9427 0.9680 0.9259 32

Under normality the coverage is 0.95 within the Monte Carlo error at every nn, even n=2n = 2. For skewed data the two-sided coverage is too low and the two one-sided bounds err in opposite directions: when the sample mean is low, SS also tends to be low, so the upper bound misses μ\mu far more often than 5%. At n=100n = 100 the upper bound still covers only 0.926. The interval Xˉ±1.96 S/n\bar X \pm 1.96\,S/\sqrt n on normal data with n=5n = 5 covers 0.8771 (same rr, seed 33).

Correctness

By Helmert's transformation, Xˉ\bar X and S2S^2 are independent under normality, n(Xˉ−μ)/σ\sqrt n(\bar X - \mu)/\sigma is standard normal and (n−1)S2/σ2(n - 1)S^2/\sigma^2 is chi-square with n−1n - 1 degrees of freedom, so the pivot QQ is tn−1t_{n-1} and its law does not involve μ\mu or σ\sigma. The event {L≤μ≤U}\{L \le \mu \le U\} is the event {∣Q∣≤t(n−1,1−α/2)}\{|Q| \le t_{(n-1, 1-\alpha/2)}\}, whose probability is 1−α1 - \alpha by the symmetry and continuity of tn−1t_{n-1}. The one-sided bounds are the events Q≤t(n−1,1−α)Q \le t_{(n-1, 1-\alpha)} and Q≥−t(n−1,1−α)Q \ge -t_{(n-1, 1-\alpha)}. Duality follows because the two-sided p-value is a strictly decreasing function of ∣xˉ−μ0∣|\bar x - \mu_0| that equals α\alpha at the end points. Without normality, QQ tends to N(0,1)N(0, 1) and the quantiles tend to the normal ones. The proofs are in the correctness proof below.

Proof: The t interval has coverage exactly 1 - alpha under normal iid data, is dual to the t-test, and has the stated expected widthfull

We prove that the three intervals returned by the code cover the mean with probability exactly 1−α1 - \alpha for every μ\mu and σ\sigma when the data are iid normal, that the two-sided interval is the set of null values the two-sided t-test does not reject, that without normality the coverage tends to 1−α1 - \alpha, and we compute the expected width. X1,…,XnX_1, \dots, X_n are iid N(μ,σ2)N(\mu, \sigma^2), n≥2n \ge 2, S2S^2 has the divisor n−1n - 1, ν=n−1\nu = n - 1, and qp=t(ν,p)q_p = t_{(\nu, p)} is the lower pp quantile of tνt_\nu.

Lemma 1 (the pivot). Q=(Xˉ−μ)/(S/n)Q = (\bar X - \mu)/(S/\sqrt n) has the tn−1t_{n-1} law for every μ\mu and every σ>0\sigma > 0.

Proof. This is Lemma 2 of the correctness proof of Student's t-test with μ0=μ\mu_0 = \mu, so λ=0\lambda = 0: by Helmert's transformation, n(Xˉ−μ)/σ∼N(0,1)\sqrt n(\bar X - \mu)/\sigma \sim N(0, 1) is independent of (n−1)S2/σ2∼χn−12(n - 1)S^2/\sigma^2 \sim \chi^2_{n-1}, and their ratio, with σ\sigma cancelled, is tn−1t_{n-1} by definition. □\square

A pivot is a function of the data and the parameter whose law does not depend on any parameter. Lemma 1 is the whole reason the interval is exact.

Lemma 2 (exact coverage). For every μ\mu and σ>0\sigma > 0:

  1. P(Xˉ−q1−α/2S/n≤μ≤Xˉ+q1−α/2S/n)=1−αP\big(\bar X - q_{1-\alpha/2}S/\sqrt n \le \mu \le \bar X + q_{1-\alpha/2}S/\sqrt n\big) = 1 - \alpha;
  2. P(μ≥Xˉ−q1−αS/n)=1−αP\big(\mu \ge \bar X - q_{1-\alpha}S/\sqrt n\big) = 1 - \alpha (lower bound);
  3. P(μ≤Xˉ+q1−αS/n)=1−αP\big(\mu \le \bar X + q_{1-\alpha}S/\sqrt n\big) = 1 - \alpha (upper bound).

Proof. S>0S > 0 with probability 1, because the XiX_i are all equal with probability 0 for a continuous law. Dividing by S/n>0S/\sqrt n > 0 keeps the inequalities. Event 1 is {−q1−α/2≤Q≤q1−α/2}\{-q_{1-\alpha/2} \le Q \le q_{1-\alpha/2}\}. The tνt_\nu law is continuous and symmetric, so qα/2=−q1−α/2q_{\alpha/2} = -q_{1-\alpha/2} and the event has probability (1−α/2)−α/2=1−α(1 - \alpha/2) - \alpha/2 = 1 - \alpha by Lemma 1. Event 2 is {Q≤q1−α}\{Q \le q_{1-\alpha}\}, with probability 1−α1 - \alpha. Event 3 is {Q≥−q1−α}={Q≥qα}\{Q \ge -q_{1-\alpha}\} = \{Q \ge q_\alpha\}, with probability 1−α1 - \alpha because P(Q=qα)=0P(Q = q_\alpha) = 0. The probabilities do not depend on (μ,σ)(\mu, \sigma), so the infimum over the parameter space, which is the confidence coefficient, is also 1−α1 - \alpha. □\square

The probability in Lemma 2 is over the sample. For a fixed computed interval, μ\mu either lies in it or does not; the statement is about the procedure.

Lemma 3 (duality with the t-test). Let p(μ0)=2Fˉν(∣xˉ−μ0∣/(s/n))p(\mu_0) = 2\bar F_\nu\big(|\bar x - \mu_0|/(s/\sqrt n)\big) be the two-sided t-test p-value for H0:μ=μ0H_0: \mu = \mu_0 on data with s>0s > 0. Then p(μ0)≥αp(\mu_0) \ge \alpha if and only if μ0\mu_0 lies in the closed interval xˉ±q1−α/2s/n\bar x \pm q_{1-\alpha/2}s/\sqrt n, and p(μ0)>αp(\mu_0) > \alpha if and only if μ0\mu_0 lies in its interior. The same holds for the one-sided bounds and one-sided tests.

Proof. Fˉν\bar F_\nu is continuous and strictly decreasing, and Fˉν(q1−α/2)=α/2\bar F_\nu(q_{1-\alpha/2}) = \alpha/2. So p(μ0)≥αp(\mu_0) \ge \alpha iff ∣xˉ−μ0∣/(s/n)≤q1−α/2|\bar x - \mu_0|/(s/\sqrt n) \le q_{1-\alpha/2} iff ∣xˉ−μ0∣≤q1−α/2s/n|\bar x - \mu_0| \le q_{1-\alpha/2}s/\sqrt n, and the strict versions match. For the lower bound, the "greater" test of H0:μ≤μ0H_0: \mu \le \mu_0 has p=Fˉν((xˉ−μ0)/(s/n))p = \bar F_\nu\big((\bar x - \mu_0)/(s/\sqrt n)\big), and p≥αp \ge \alpha iff μ0≥xˉ−q1−αs/n\mu_0 \ge \bar x - q_{1-\alpha}s/\sqrt n; the upper bound is symmetric. □\square

The test rejects when p≤αp \le \alpha, so the closed interval contains the set of values it does not reject plus its two end points, where the p-value is exactly α\alpha. This event of probability 0 is why the closed and the open interval have the same coverage.

Lemma 4 (one-sided bounds from the two-sided interval). The 1−α1 - \alpha lower bound equals the left end of the two-sided 1−2α1 - 2\alpha interval, and the 1−α1 - \alpha upper bound equals its right end.

Proof. Both use the quantile q1−α=q1−(2α)/2q_{1-\alpha} = q_{1 - (2\alpha)/2} and the same Xˉ\bar X and SS. □\square

Lemma 5 (expected width). The two-sided interval has width 2q1−α/2S/n2q_{1-\alpha/2}S/\sqrt n, and E[S]=c4(n)σE[S] = c_4(n)\sigma with c4(n)=2/(n−1) Γ(n/2)/Γ((n−1)/2)c_4(n) = \sqrt{2/(n - 1)}\,\Gamma(n/2)/\Gamma((n - 1)/2), so the expected width is 2q1−α/2c4(n)σ/n2q_{1-\alpha/2}c_4(n)\sigma/\sqrt n.

Proof. S=σV/(n−1)S = \sigma\sqrt{V/(n - 1)} with V∼χk2V \sim \chi^2_k, k=n−1k = n - 1. With the χk2\chi^2_k density vk/2−1e−v/2/(2k/2Γ(k/2))v^{k/2-1}e^{-v/2}/(2^{k/2}\Gamma(k/2)),

E[V]=12k/2Γ(k/2)∫0∞v(k+1)/2−1e−v/2 dv=2(k+1)/2Γ((k+1)/2)2k/2Γ(k/2)=2 Γ((k+1)/2)Γ(k/2),E[\sqrt V] = \frac{1}{2^{k/2}\Gamma(k/2)}\int_0^\infty v^{(k+1)/2-1}e^{-v/2}\,dv = \frac{2^{(k+1)/2}\Gamma((k + 1)/2)}{2^{k/2}\Gamma(k/2)} = \sqrt 2\,\frac{\Gamma((k + 1)/2)}{\Gamma(k/2)} ,

so E[S]=σ2/k Γ(n/2)/Γ((n−1)/2)E[S] = \sigma\sqrt{2/k}\,\Gamma(n/2)/\Gamma((n - 1)/2). □\square

Lemma 6 (without normality). Let X1,…,XnX_1, \dots, X_n be iid with mean μ\mu and finite variance σ2>0\sigma^2 > 0. Then the coverage of each of the three intervals tends to 1−α1 - \alpha as n→∞n \to \infty.

Proof. By Lemma 7 of the Student proof (the central limit theorem and Slutsky's theorem), QQ converges in distribution to N(0,1)N(0, 1), and q1−α/2→z1−α/2q_{1-\alpha/2} \to z_{1-\alpha/2}, q1−α→z1−αq_{1-\alpha} \to z_{1-\alpha}. The coverage events are {∣Q∣≤q1−α/2}\{|Q| \le q_{1-\alpha/2}\}, {Q≤q1−α}\{Q \le q_{1-\alpha}\} and {Q≥−q1−α}\{Q \ge -q_{1-\alpha}\}, and the limit law is continuous, so their probabilities tend to 1−α1 - \alpha. □\square

The convergence is not uniform over the distributions with finite variance, so no fixed nn guarantees a coverage close to 1−α1 - \alpha for every such distribution.

Termination. The code makes two passes over nn numbers. The quantile is computed by bisection on the tνt_\nu upper tail: the bracket is doubled until it contains the quantile, which takes finitely many steps because Fˉν(x)→0\bar F_\nu(x) \to 0, and then halved at most 400 times or until no double lies strictly between the end points. Each tail evaluation is a continued fraction with an iteration cap. So the procedure stops.

Theorem. Under iid normal data, the two-sided t interval and the one-sided t bounds computed by the code have coverage exactly 1−α1 - \alpha for every μ\mu, σ\sigma and n≥2n \ge 2; the two-sided interval is the closure of the set of μ0\mu_0 that the two-sided level α\alpha t-test does not reject; and for iid data with finite positive variance the coverage tends to 1−α1 - \alpha.

Proof. Lemmas 1 and 2 for the coverage, Lemma 3 for the duality, and Lemma 6 for the limit. ■\blacksquare

Complexity

On a real RAM, L2 and L3 make two passes, about 4n4n arithmetic operations, and L4 to L9 a constant number. The quantile costs a bisection of at most a few hundred halvings, each an incomplete beta evaluation whose cost does not grow with nn, and it is computed once per (1−α,n)(1 - \alpha, n). So the time is Θ(n)\Theta(n) and the extra space Θ(1)\Theta(1) besides the data. L3 uses the two-pass formula; the one-pass ∑xi2−nxˉ2\sum x_i^2 - n\bar x^2 suffers catastrophic cancellation when the mean is large compared with the spread.

Properties

  • Exact. Coverage exactly 1−α1 - \alpha for every μ\mu, σ\sigma and n≥2n \ge 2 under iid normal data.
  • Equivariant. If every xix_i is replaced by a+bxia + b x_i with b≠0b \ne 0, the interval is mapped by the same affine map (with its ends swapped when b<0b < 0).
  • Random width. The width 2t(n−1,1−α/2)S/n2t_{(n-1, 1-\alpha/2)}S/\sqrt n varies from sample to sample. Its expectation is 2t(n−1,1−α/2)c4(n)σ/n2t_{(n-1, 1-\alpha/2)}c_4(n)\sigma/\sqrt n with c4(n)=2/(n−1) Γ(n/2)/Γ((n−1)/2)c_4(n) = \sqrt{2/(n - 1)}\,\Gamma(n/2)/\Gamma((n - 1)/2). For 95% intervals the expected width in units of σ\sigma is 14.34 at n=2n = 2, 4.40 at n=3n = 3, 2.334 at n=5n = 5, 1.392 at n=10n = 10 and 0.740 at n=30n = 30, against 2×1.96/n2 \times 1.96/\sqrt n = 2.772, 2.263, 1.753, 1.240 and 0.716 for the z interval with σ\sigma known.
  • Optimal among unbiased intervals. It inverts the uniformly most powerful unbiased family of t-tests, so it is uniformly most accurate unbiased: it covers each false value with the smallest possible probability (Lehmann and Romano, Sections 5.4 and 5.5).
  • One-sided bounds. The 1−α1 - \alpha lower bound is the left end of the two-sided 1−2α1 - 2\alpha interval.

Variants and improvements

  • z interval. With σ\sigma known, Xˉ±z1−α/2σ/n\bar X \pm z_{1-\alpha/2}\sigma/\sqrt n is exact and has a fixed width; see the z-test.
  • Paired and two-sample intervals. The interval for a mean difference of paired data is the t interval of the differences. For two independent samples, the pooled interval uses SpS_p and m+n−2m + n - 2 degrees of freedom (exact under equal variances), and the Welch interval uses separate variances and the Welch-Satterthwaite degrees of freedom (approximate).
  • Bootstrap intervals. The bootstrap percentile-t interval estimates the law of QQ from the data. It corrects the one-sided errors for skewed data at a rate faster than the normal approximation, but is still approximate.
  • Intervals for a proportion. For binomial data the analogue is the Wilson score or Clopper-Pearson interval, not a t interval.
  • Prediction interval. Xˉ±t(n−1,1−α/2)S1+1/n\bar X \pm t_{(n-1, 1-\alpha/2)}S\sqrt{1 + 1/n} covers the next observation, not the mean, with probability 1−α1 - \alpha under normality; see prediction interval.
  • Credible interval. Under the improper prior with density proportional to 1/σ1/\sigma, the Bayesian posterior of μ\mu is xˉ+(s/n)tn−1\bar x + (s/\sqrt n)t_{n-1}, so the equal-tailed credible interval has the same end points. The numbers agree; the statements do not: the credible interval assigns posterior probability 1−α1 - \alpha to μ\mu given the data, while the confidence statement is about the procedure over repeated samples.

When to use it

Use the t interval for the mean of one sample, or of paired differences, when σ\sigma is unknown and the data are close to normal, or when nn is large and the data are not strongly skewed. Report it together with or instead of a t-test p-value: it shows both the estimate and its precision. For strongly skewed data with small nn, or for one-sided bounds on skewed data even at n=100n = 100, use a transformation, a bootstrap interval or a method built for the distribution.

Pitfalls

  • Reading 95% as a probability for the computed interval. For the sleep data, μ\mu is in [0.7001,2.4599][0.7001, 2.4599] or not; the 0.95 is the long-run hit rate of the procedure.
  • Using zz quantiles with SS. At n=5n = 5 the interval Xˉ±1.96 S/n\bar X \pm 1.96\,S/\sqrt n covers only about 0.88.
  • Trusting one-sided bounds on skewed data. The upper 95% bound for exponential data covers 0.84 at n=5n = 5 and 0.93 at n=100n = 100.
  • Applying it to dependent data. Autocorrelated measurements make S/nS/\sqrt n a wrong standard error, and the coverage can be far from nominal at any nn.
  • Comparing two groups by overlap of their intervals. Two 95% intervals can overlap while the two-sample test rejects at 5%; use an interval for the difference.
  • Choosing the level after seeing the data. Picking the level that just excludes 0 turns the interval into a p-value with the wrong meaning.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

stdist.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Normal, chi-square, t and F distribution functions in the standard library.

The incomplete gamma and beta functions return a lower tail and an upper
tail, and each tail is computed directly where it is small, so an upper tail
such as chi2_sf(200, 3) does not come from 1 - cdf and does not cancel.
Quantiles use a safeguarded bisection on the CDF (lower half) or on the upper
tail (upper half); the bracket shrinks until floating point stops it, so the
probability error is that of the CDF, below 1e-12 for moderate parameters.
"""

import math
from statistics import NormalDist

_STD = NormalDist()
_EPS = 1e-16
_TINY = 1e-300
_MAXIT = 10000


def norm_cdf(x: float) -> float:
    """P(Z <= x) for a standard normal Z."""
    return 0.5 * math.erfc(-x / math.sqrt(2.0))


def norm_sf(x: float) -> float:
    """P(Z > x), computed with erfc, so it is accurate for large x."""
    return 0.5 * math.erfc(x / math.sqrt(2.0))


def norm_ppf(p: float) -> float:
    """The lower p-quantile z_p of the standard normal, 0 < p < 1."""
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    return _STD.inv_cdf(p)


def _gamma_tails(a: float, x: float) -> tuple[float, float]:
    """(P(a, x), Q(a, x)), the regularized lower and upper incomplete gamma."""
    if a <= 0.0 or x < 0.0:
        raise ValueError("need a > 0 and x >= 0")
    if x == 0.0:
        return 0.0, 1.0
    if math.isinf(x):
        return 1.0, 0.0
    front = math.exp(-x + a * math.log(x) - math.lgamma(a))
    if x < a + 1.0:
        # Series: P = front * sum_{j >= 0} x^j / (a (a + 1) ... (a + j)).
        ap, term = a, 1.0 / a
        total = term
        for _ in range(_MAXIT):
            ap += 1.0
            term *= x / ap
            total += term
            if abs(term) < abs(total) * _EPS:
                break
        p = front * total
        return p, 1.0 - p
    # Continued fraction for Q, modified Lentz.
    b = x + 1.0 - a
    c = 1.0 / _TINY
    d = 1.0 / b
    h = d
    for i in range(1, _MAXIT):
        an = -i * (i - a)
        b += 2.0
        d = an * d + b
        if abs(d) < _TINY:
            d = _TINY
        c = b + an / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        step = d * c
        h *= step
        if abs(step - 1.0) < _EPS:
            break
    q = front * h
    return 1.0 - q, q


def gamma_p(a: float, x: float) -> float:
    """Regularized lower incomplete gamma P(a, x)."""
    return _gamma_tails(a, x)[0]


def gamma_q(a: float, x: float) -> float:
    """Regularized upper incomplete gamma Q(a, x) = 1 - P(a, x)."""
    return _gamma_tails(a, x)[1]


def _beta_cf(a: float, b: float, x: float) -> float:
    """The continued fraction of I_x(a, b), modified Lentz."""
    qab, qap, qam = a + b, a + 1.0, a - 1.0
    c = 1.0
    d = 1.0 - qab * x / qap
    if abs(d) < _TINY:
        d = _TINY
    d = 1.0 / d
    h = d
    for m in range(1, _MAXIT):
        m2 = 2 * m
        aa = m * (b - m) * x / ((qam + m2) * (a + m2))
        d = 1.0 + aa * d
        if abs(d) < _TINY:
            d = _TINY
        c = 1.0 + aa / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        h *= d * c
        aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
        d = 1.0 + aa * d
        if abs(d) < _TINY:
            d = _TINY
        c = 1.0 + aa / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        step = d * c
        h *= step
        if abs(step - 1.0) < _EPS:
            break
    return h


def _beta_tails(a: float, b: float, x: float, y: float | None = None) -> tuple[float, float]:
    """(I_x(a, b), 1 - I_x(a, b)), each computed directly where it is small.

    y is 1 - x; pass it when it is known more accurately than 1 - x.
    """
    if a <= 0.0 or b <= 0.0:
        raise ValueError("need a > 0 and b > 0")
    if y is None:
        y = 1.0 - x
    if x <= 0.0:
        return 0.0, 1.0
    if y <= 0.0:
        return 1.0, 0.0
    front = math.exp(
        math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
        + a * math.log(x) + b * math.log(y)
    )
    if x < (a + 1.0) / (a + b + 2.0):
        low = front * _beta_cf(a, b, x) / a
        return low, 1.0 - low
    # Symmetry: I_x(a, b) = 1 - I_(1-x)(b, a).
    up = front * _beta_cf(b, a, y) / b
    return 1.0 - up, up


def beta_inc(a: float, b: float, x: float) -> float:
    """Regularized incomplete beta function I_x(a, b)."""
    return _beta_tails(a, b, x)[0]


def chi2_cdf(x: float, k: float) -> float:
    """P(X <= x) for X chi-square with k > 0 degrees of freedom."""
    return 0.0 if x <= 0.0 else gamma_p(k / 2.0, x / 2.0)


def chi2_sf(x: float, k: float) -> float:
    """P(X > x) for X chi-square with k degrees of freedom, without 1 - cdf."""
    return 1.0 if x <= 0.0 else gamma_q(k / 2.0, x / 2.0)


def t_sf(x: float, k: float) -> float:
    """P(T > x) for T Student t with k > 0 degrees of freedom."""
    if math.isfinite(x):
        s = k + x * x
        half = 0.5 * _beta_tails(k / 2.0, 0.5, k / s, x * x / s)[0]  # P(|T| > |x|) / 2
    else:
        half = 0.0
    return half if x >= 0.0 else 1.0 - half


def t_cdf(x: float, k: float) -> float:
    """P(T <= x) for T Student t with k degrees of freedom."""
    return t_sf(-x, k)


def f_cdf(x: float, k1: float, k2: float) -> float:
    """P(F <= x) for F with (k1, k2) degrees of freedom."""
    if x <= 0.0:
        return 0.0
    return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[1]


def f_sf(x: float, k1: float, k2: float) -> float:
    """P(F > x) = I_(k2 / (k2 + k1 x))(k2 / 2, k1 / 2)."""
    if x <= 0.0:
        return 1.0
    return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[0]


def _quantile(cdf, sf, p: float, lo: float, hi: float) -> float:
    """The x with cdf(x) = p, by bisection on cdf (p <= 1/2) or on sf (p > 1/2).

    lo must satisfy cdf(lo) <= p; hi is doubled until cdf(hi) >= p.
    """
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    if p <= 0.5:
        g = lambda x: cdf(x) - p  # increasing in x
    else:
        q = 1.0 - p
        g = lambda x: q - sf(x)  # increasing in x, and no cancellation in sf
    while g(hi) < 0.0:
        lo, hi = hi, 2.0 * hi if hi > 0.0 else 1.0
    for _ in range(400):
        mid = 0.5 * (lo + hi)
        if mid <= lo or mid >= hi:
            break
        if g(mid) < 0.0:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)


def chi2_ppf(p: float, k: float) -> float:
    """The lower p-quantile chi^2_(k, p)."""
    return _quantile(lambda x: chi2_cdf(x, k), lambda x: chi2_sf(x, k), p, 0.0, max(1.0, k))


def t_ppf(p: float, k: float) -> float:
    """The lower p-quantile t_(k, p)."""
    if p == 0.5:
        return 0.0
    if p < 0.5:
        return -t_ppf(1.0 - p, k)
    return _quantile(lambda x: t_cdf(x, k), lambda x: t_sf(x, k), p, 0.0, 1.0)


def f_ppf(p: float, k1: float, k2: float) -> float:
    """The lower p-quantile F_(k1, k2, p)."""
    return _quantile(lambda x: f_cdf(x, k1, k2), lambda x: f_sf(x, k1, k2), p, 0.0, 1.0)
t_confidence_interval.py 43 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/t-confidence-interval/. The authors are listed in prov/W2JAG5.jsonl.
"""The Student t confidence interval for a normal mean with unknown variance.

t_interval returns (lower, upper). side = "two-sided" gives
x-bar -+ t_(n-1, 1-alpha/2) S / sqrt(n); side = "lower" gives the lower
confidence bound [x-bar - t_(n-1, 1-alpha) S / sqrt(n), inf); side = "upper"
gives (-inf, x-bar + t_(n-1, 1-alpha) S / sqrt(n)]. S^2 has the divisor
n - 1 and is computed by two passes.
"""

import math
from collections.abc import Sequence
from functools import lru_cache

from stdist import t_ppf as _t_ppf

SIDES = ("two-sided", "lower", "upper")

# The quantile depends only on (p, n - 1); repeated calls, as in a simulation, reuse it.
t_ppf = lru_cache(maxsize=1024)(_t_ppf)


def t_interval(x: Sequence[float], confidence: float = 0.95,
               side: str = "two-sided") -> tuple[float, float]:
    """A confidence interval for the mean of iid normal data, exact coverage `confidence`."""
    if not 0.0 < confidence < 1.0:
        raise ValueError("confidence must be in (0, 1)")
    if side not in SIDES:
        raise ValueError(f"side must be one of {SIDES}")
    n = len(x)  # @line L1
    if n < 2:
        raise ValueError("need at least 2 observations")
    mean = math.fsum(x) / n  # @line L2
    s2 = math.fsum((v - mean) ** 2 for v in x) / (n - 1)  # @line L3
    se = math.sqrt(s2 / n)  # @line L4
    if side == "two-sided":
        q = t_ppf(1.0 - (1.0 - confidence) / 2.0, n - 1)  # @line L5
        return mean - q * se, mean + q * se  # @line L6
    q = t_ppf(confidence, n - 1)  # @line L7
    if side == "lower":
        return mean - q * se, math.inf  # @line L8
    return -math.inf, mean + q * se  # @line L9
test_t_confidence_interval.py 102 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/t-confidence-interval/. The authors are listed in prov/W2JAG5.jsonl.

import math
import random

import pytest

from stdist import t_sf
from t_confidence_interval import t_interval

SLEEP_DIFFERENCES = [1.2, 2.4, 1.3, 1.3, 0.0, 1.0, 1.8, 0.8, 4.6, 1.4]
R = 4000
SE4 = 4.0 * math.sqrt(0.05 * 0.95 / R)  # four standard errors of a coverage near 0.95


def test_sleep_data() -> None:
    lo, hi = t_interval(SLEEP_DIFFERENCES)
    # 1.58 -+ t_(9, 0.975) * 0.388959..., with t_(9, 0.975) = 2.262157...
    assert abs(lo - 0.7001) < 1e-4 and abs(hi - 2.4599) < 1e-4
    assert abs((lo + hi) / 2 - 1.58) < 1e-12


def test_closed_form_quantiles() -> None:
    # nu = 1 is the Cauchy law: t_(1, p) = tan(pi (p - 1/2)). With n = 2, S = |x1 - x2| / sqrt(2),
    # so the 95% interval is the mean -+ tan(0.475 pi) |x1 - x2| / 2.
    lo, hi = t_interval([3.0, 7.0])
    q1 = math.tan(0.475 * math.pi)
    assert abs(q1 - 12.706204736174698) < 1e-9
    assert abs(lo - (5.0 - 2.0 * q1)) < 1e-9 and abs(hi - (5.0 + 2.0 * q1)) < 1e-9
    # nu = 2: t_(2, p) = (2p - 1) / sqrt(2 p (1 - p)).
    lo, hi = t_interval([1.0, 2.0, 6.0], confidence=0.9)
    q2 = 0.9 / math.sqrt(2 * 0.95 * 0.05)
    se = math.sqrt(7.0 / 3.0)  # S^2 = 7 with divisor n - 1 = 2
    assert abs(hi - lo - 2.0 * q2 * se) < 1e-9


def test_duality_with_the_t_test() -> None:
    rng = random.Random(21)
    for _ in range(30):
        n = rng.randint(2, 15)
        x = [rng.gauss(10.0, 3.0) for _ in range(n)]
        lo, hi = t_interval(x, 0.95)
        mean = sum(x) / n
        se = math.sqrt(sum((v - mean) ** 2 for v in x) / (n - 1) / n)
        p = lambda mu0: 2.0 * t_sf(abs(mean - mu0) / se, n - 1)
        # At the end points the two-sided p-value is alpha; inside it is larger, outside smaller.
        assert abs(p(lo) - 0.05) < 1e-9 and abs(p(hi) - 0.05) < 1e-9
        assert p((lo + hi) / 2) > 0.05
        assert p(hi + 0.01 * (hi - lo)) < 0.05


def test_one_sided_bounds() -> None:
    rng = random.Random(22)
    x = [rng.gauss(0.0, 1.0) for _ in range(12)]
    lo90, hi90 = t_interval(x, 0.90)
    lower, inf = t_interval(x, 0.95, "lower")
    minf, upper = t_interval(x, 0.95, "upper")
    assert inf == math.inf and minf == -math.inf
    # A 95% one-sided bound is an end point of the 90% two-sided interval.
    assert abs(lower - lo90) < 1e-12 and abs(upper - hi90) < 1e-12


def test_equivariance() -> None:
    rng = random.Random(23)
    x = [rng.gauss(0.0, 1.0) for _ in range(9)]
    lo, hi = t_interval(x)
    lo2, hi2 = t_interval([3.0 - 2.5 * v for v in x])
    assert abs(lo2 - (3.0 - 2.5 * hi)) < 1e-12 and abs(hi2 - (3.0 - 2.5 * lo)) < 1e-12


def coverage(draw, mu: float, n: int, side: str, seed: int) -> float:
    rng = random.Random(seed)
    hits = 0
    for _ in range(R):
        lo, hi = t_interval([draw(rng) for _ in range(n)], 0.95, side)
        hits += lo <= mu <= hi
    return hits / R


def test_exact_coverage_for_normal_data() -> None:
    for n, seed in ((2, 1), (5, 2), (20, 3)):
        assert abs(coverage(lambda g: g.gauss(4.0, 2.0), 4.0, n, "two-sided", seed) - 0.95) < SE4
    assert abs(coverage(lambda g: g.gauss(4.0, 2.0), 4.0, 5, "upper", 4) - 0.95) < SE4


def test_under_coverage_for_skewed_data() -> None:
    # Exponential data with mean 1, n = 5: only asymptotic. The two-sided coverage is about 0.88,
    # the upper bound covers about 0.85 and the lower bound about 0.99.
    expo = lambda g: g.expovariate(1.0)
    assert coverage(expo, 1.0, 5, "two-sided", 5) < 0.95 - SE4
    assert coverage(expo, 1.0, 5, "upper", 6) < 0.95 - SE4
    assert coverage(expo, 1.0, 5, "lower", 7) > 0.95 + SE4


def test_bad_input() -> None:
    with pytest.raises(ValueError):
        t_interval([1.0])
    with pytest.raises(ValueError):
        t_interval([1.0, 2.0], confidence=1.0)
    with pytest.raises(ValueError):
        t_interval([1.0, 2.0], side="both")

History

Student's 1908 paper gave the law of (xˉ−μ)/s(\bar x - \mu)/s for normal samples and used it to state probable limits for a mean. R. A. Fisher reached the same numerical limits with his fiducial argument from 1930. Jerzy Neyman's 1937 paper in the Philosophical Transactions of the Royal Society set out the theory of confidence intervals: a confidence coefficient is the probability, over repeated samples, that the random interval covers the fixed parameter, and a computed interval either contains the parameter or does not. The t interval is the standard example of that theory.

References

  1. Jerzy Neyman, Outline of a theory of statistical estimation based on the classical theory of probability, Philosophical Transactions of the Royal Society A 236, 1937, pp. 333 to 380, The whole paper (confidence intervals, the coverage probability as a property of the procedure, and the statement that a computed interval contains the parameter or does not)
  2. Student, The probable error of a mean, Biometrika 6(1), 1908, pp. 1 to 25, The whole paper (the law of the standardized mean for normal samples, the pivot behind the interval)
  3. George Casella and Roger L. Berger, Statistical Inference, second edition, Duxbury, 2002, Section 9.2.1 (inverting a test statistic, the t interval as the inverted t-test) and Section 9.2.2 (pivotal quantities)
  4. E. L. Lehmann and Joseph P. Romano, Testing Statistical Hypotheses, third edition, Springer, 2005, Section 5.4 (confidence intervals and families of tests) and Section 5.5 (unbiased confidence sets)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example