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
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- William Sealy Gosset, Jerzy Neyman, 1937
The Student t confidence interval for the mean of a normal population with unknown standard deviation is , where is the sample variance with divisor and is the lower quantile of the t distribution with degrees of freedom. Under iid normal data its confidence coverage is exactly for every , and : 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. iid with and unknown, , and a confidence level . Find a random interval , a function of the data only, with for all , as short as possible.
Pivot. has the law for every and .
Interval. Two-sided: . Lower confidence bound: . Upper confidence bound: .
Coverage type. Exact: under the model the coverage equals 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 as by the central limit theorem and Slutsky's theorem; it is then asymptotic, and not uniformly so.
Duality. lies in the open interval exactly when the two-sided level- t-test of does not reject, that is when its p-value exceeds ; at the two end points the p-value equals .
The algorithm
T-INTERVAL(x[1..n], 1 − α, side) ▷ n ≥ 2- 1
n ← the length of x - 2
x̄ ← (x[1] + ... + x[n]) / n - 3
S² ← ((x[1] − x̄)² + ... + (x[n] − x̄)²) / (n − 1) ▷ second pass, divisor n − 1 - 4
se ← √(S² / n) - 5
if side = two-sided then q ← t_(n−1, 1−α/2) - 6
return [x̄ − q · se, x̄ + q · se] - 7
q ← t_(n−1, 1−α) - 8
if side = lower then return [x̄ − q · se, ∞) - 9
return (−∞, x̄ + q · se]
The quantile is found by bisection on the upper tail , which the helper evaluates by the continued fraction of the regularized incomplete beta function: for . Bisecting on the upper tail, not on , keeps the digits of small tail probabilities. The code caches the quantile for each , which matters when the interval is computed many times, as in a simulation. If all values are equal, and the interval is the single point ; 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 . A 95% interval for the mean difference:
| line | value |
|---|---|
| L2: | |
| L3: | |
| L4: | |
| L5: | |
| L6: |
The interval excludes 0, matching the t-test p-value of 0.0028. The 99% interval, with , is , and the 95% lower bound, with , is . Using 1.96 in place of 2.262157 would give , which is too short.
Coverage. Monte Carlo with replications of nominal 95% intervals (standard error of an estimated coverage near 0.95: 0.0015):
| data | two-sided | lower bound | upper bound | seed | |
|---|---|---|---|---|---|
| normal, , | 2 | 0.9507 | 31 | ||
| normal, , | 5 | 0.9530 | 31 | ||
| normal, , | 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 , even . 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, also tends to be low, so the upper bound misses far more often than 5%. At the upper bound still covers only 0.926. The interval on normal data with covers 0.8771 (same , seed 33).
Correctness
By Helmert's transformation, and are independent under normality, is standard normal and is chi-square with degrees of freedom, so the pivot is and its law does not involve or . The event is the event , whose probability is by the symmetry and continuity of . The one-sided bounds are the events and . Duality follows because the two-sided p-value is a strictly decreasing function of that equals at the end points. Without normality, tends to 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 for every and 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 , and we compute the expected width. are iid , , has the divisor , , and is the lower quantile of .
Lemma 1 (the pivot). has the law for every and every .
Proof. This is Lemma 2 of the correctness proof of Student's t-test with , so : by Helmert's transformation, is independent of , and their ratio, with cancelled, is by definition.
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 and :
- ;
- (lower bound);
- (upper bound).
Proof. with probability 1, because the are all equal with probability 0 for a continuous law. Dividing by keeps the inequalities. Event 1 is . The law is continuous and symmetric, so and the event has probability by Lemma 1. Event 2 is , with probability . Event 3 is , with probability because . The probabilities do not depend on , so the infimum over the parameter space, which is the confidence coefficient, is also .
The probability in Lemma 2 is over the sample. For a fixed computed interval, either lies in it or does not; the statement is about the procedure.
Lemma 3 (duality with the t-test). Let be the two-sided t-test p-value for on data with . Then if and only if lies in the closed interval , and if and only if lies in its interior. The same holds for the one-sided bounds and one-sided tests.
Proof. is continuous and strictly decreasing, and . So iff iff , and the strict versions match. For the lower bound, the "greater" test of has , and iff ; the upper bound is symmetric.
The test rejects when , so the closed interval contains the set of values it does not reject plus its two end points, where the p-value is exactly . 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 lower bound equals the left end of the two-sided interval, and the upper bound equals its right end.
Proof. Both use the quantile and the same and .
Lemma 5 (expected width). The two-sided interval has width , and with , so the expected width is .
Proof. with , . With the density ,
so .
Lemma 6 (without normality). Let be iid with mean and finite variance . Then the coverage of each of the three intervals tends to as .
Proof. By Lemma 7 of the Student proof (the central limit theorem and Slutsky's theorem), converges in distribution to , and , . The coverage events are , and , and the limit law is continuous, so their probabilities tend to .
The convergence is not uniform over the distributions with finite variance, so no fixed guarantees a coverage close to for every such distribution.
Termination. The code makes two passes over numbers. The quantile is computed by bisection on the upper tail: the bracket is doubled until it contains the quantile, which takes finitely many steps because , 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 for every , and ; the two-sided interval is the closure of the set of that the two-sided level t-test does not reject; and for iid data with finite positive variance the coverage tends to .
Proof. Lemmas 1 and 2 for the coverage, Lemma 3 for the duality, and Lemma 6 for the limit.
Complexity
On a real RAM, L2 and L3 make two passes, about 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 , and it is computed once per . So the time is and the extra space besides the data. L3 uses the two-pass formula; the one-pass suffers catastrophic cancellation when the mean is large compared with the spread.
Properties
- Exact. Coverage exactly for every , and under iid normal data.
- Equivariant. If every is replaced by with , the interval is mapped by the same affine map (with its ends swapped when ).
- Random width. The width varies from sample to sample. Its expectation is with . For 95% intervals the expected width in units of is 14.34 at , 4.40 at , 2.334 at , 1.392 at and 0.740 at , against = 2.772, 2.263, 1.753, 1.240 and 0.716 for the z interval with 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 lower bound is the left end of the two-sided interval.
Variants and improvements
- z interval. With known, 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 and 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 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. covers the next observation, not the mean, with probability under normality; see prediction interval.
- Credible interval. Under the improper prior with density proportional to , the Bayesian posterior of is , so the equal-tailed credible interval has the same end points. The numbers agree; the statements do not: the credible interval assigns posterior probability to 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 is unknown and the data are close to normal, or when 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 , or for one-sided bounds on skewed data even at , 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, is in or not; the 0.95 is the long-run hit rate of the procedure.
- Using quantiles with . At the interval covers only about 0.88.
- Trusting one-sided bounds on skewed data. The upper 95% bound for exponential data covers 0.84 at and 0.93 at .
- Applying it to dependent data. Autocorrelated measurements make a wrong standard error, and the coverage can be far from nominal at any .
- 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.
# 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 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
- 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)
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag W2JAG5 Edit this page History Report an error Markdown