Algorithmintro
Student's t-test
Also called one-sample t-test, two-sample t-test, paired t-test.
Tests a normal mean, or two means, by the estimate over its estimated standard error. Exact t null law under normal iid data; the pooled form needs equal variances. O(n).
- Time
- Θ(n) worst · best
- Space
- Θ(1) extra
- Where
- n = the number of observations or pairs
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- William Sealy Gosset, Ronald A. Fisher, 1908
Student's t-test is a statistical hypothesis test for a mean, or for a difference of two means, when the standard deviation is unknown. It divides the estimate minus its null value by the estimated standard error, which uses the sample variance with divisor . Under iid normal data, the statistic has the t distribution with degrees of freedom exactly, for every , so the test has size exactly . It has three forms: one-sample, paired (the one-sample test on the differences) and pooled two-sample, which needs equal variances in the two groups.
In plain words
You have a few measurements and want to know if their true average is some claimed value, but you do not know how much single measurements scatter. So you estimate the scatter from the same measurements. Then you count how many estimated "typical errors" the average is away from the claim, as in the z-test. Because the scatter itself is a guess, the count varies more than a bell curve does, most of all with few measurements. Student worked out the exact law of this count for data from a bell curve, and it has heavier tails. So the cutoff for "rare" is a bit larger than two. With before and after values on the same subjects, test the differences. With two separate groups, the pooled version assumes that both groups scatter equally.
The problem
One-sample test. are iid with both and unknown, . against (two-sided), ("greater") or ("less"); for a one-sided alternative the null may be the composite or . The standard deviation is a nuisance parameter.
Statistic. With and (divisor ),
Null distribution. Exact: under , whatever is. The reason is that and are independent under normality, and is chi-square with degrees of freedom. Without normality, for iid data with finite variance, converges in distribution to by the central limit theorem and Slutsky's theorem, so the test is only asymptotic.
Rejection rule and size. With the lower quantile : reject when (two-sided), ("greater") or ("less"). Under normality the size equals , also for the composite one-sided null. For two-sided, , , , and the limit is .
p-value. With the upper tail of : ("greater"), ("less") and (two-sided). The null law is symmetric, so doubling and the "no more likely" rule agree.
Paired test. Pairs , iid over , measured on the same unit. With iid , test by the one-sample test on , with degrees of freedom. The pairs may be correlated; only the differences must be iid normal.
Pooled two-sample test. iid and iid , independent, with the same . With (divisor ),
The equal variance assumption is essential; see Pitfalls and the Welch t-test.
Sensitivity and power. The test reacts to a shift of the mean relative to the scatter. Its power depends on and only through : then has the noncentral t law with degrees of freedom and noncentrality . With 10 observations at two-sided, the power is 0.293 at and 0.803 at , against 0.353 and 0.885 for the z-test with known. That gap is the price of estimating . The one-sided t-test is uniformly most powerful among unbiased tests, and so is the two-sided one (Lehmann and Romano, Section 5.2). The power computation is on sample size determination.
The algorithm
STUDENT-T-TEST(x[1..n], μ₀, alternative) ▷ 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
t ← (x̄ − μ₀) / √(S² / n) - 5
ν ← n − 1 - 6
return (t, ν, T-P-VALUE(t, ν, alternative)) T-P-VALUE(t, ν, alternative)- 7
if alternative = two-sided then return min(1, 2 · F̄_ν(|t|)) - 8
if alternative = greater then return F̄_ν(t) - 9
if alternative = less then return F̄_ν(−t)
The upper tail is for , where is the regularized incomplete beta function. The helper evaluates it by its continued fraction, so a tail of keeps its digits. The paired test calls STUDENT-T-TEST on . The pooled test computes both means and both sums of squared deviations by two passes, forms , and calls T-P-VALUE with . If (all values equal), is undefined and the code raises an error.
Example
Student's 1908 paper used the sleep data of Cushny and Peebles: the extra hours of sleep of 10 patients under two drugs. Each patient took both drugs, so the data are paired. The differences (drug 2 minus drug 1) are
Test against at .
| line | value |
|---|---|
| L2: | |
| L3: | |
| L3: | |
| L4: | |
| L4: | |
| L5: | |
| L7: |
Since , the test rejects ; the second drug gave more sleep. The one-sided p-value for is .
Ignoring the pairing. Treat the same 20 numbers as two independent groups of 10 and run the pooled test. Then with and : no rejection at 5%. The between-patient variation, which the differences cancel, now enters the standard error. The paired design is the right one here, and the pooled analysis of paired data is a design error, not a choice of test.
Size under the model and outside it. Monte Carlo with replications at level 0.05 (standard error of an estimated size near 0.05: 0.0034):
| data | test | measured size | seed |
|---|---|---|---|
| normal, | one-sample, two-sided | 0.0478 | 1 |
| exponential with mean 1, | one-sample, two-sided | 0.1235 | 2 |
| exponential with mean 1, | one-sample, "greater" / "less" | 0.0115 / 0.1553 | 2 |
| exponential with mean 1, | one-sample, two-sided | 0.0800 | 3 |
| normal, , , | pooled | 0.0505 | 4 |
| normal, , , , | pooled | 0.3000 | 5 |
| normal, , , , | pooled | 0.0015 | 6 |
| normal, , , | pooled | 0.0593 | 7 |
The exponential rows show that skewness spoils the one-sided sizes in opposite directions and that is not yet "large". The pooled rows show the failure with unequal variances and unequal sizes. When the small group is the noisy one, is dominated by the quiet large group. Its expectation is , so the estimated variance of is about , while the true variance is . The standard error is too small by a factor , and , which matches the measured size. With equal sizes the error almost cancels.
Correctness
Under iid normal data, an orthogonal change of variables (Helmert's) whose first coordinate is turns the sample into independent normal coordinates. depends only on the first, and is the sum of squares of the other standardized coordinates. So the two are independent, the second is chi-square with degrees of freedom, and is a standard normal over the root of an independent chi-square divided by its degrees of freedom, which is the definition of . The unknown cancels. The same argument on both samples gives the pooled law when the variances are equal. The p-values are tail areas of a continuous symmetric law, so they are uniform under and the size is exactly . Without normality, in probability and Slutsky's theorem gives the normal limit. The proofs are in the correctness proof below.
Proof: Student's t statistic has the t distribution with n - 1 degrees of freedom under normal iid datafull
We prove that the statistics of the one-sample, paired and pooled t-tests have exact t null distributions under their normal models, that the returned p-values are the stated tail probabilities with size exactly , and that without normality the size tends to . Write for the t distribution with degrees of freedom: the law of where and are independent. always has the divisor .
Lemma 1 (Helmert's transformation). Let be iid , . Then and are independent, , and .
Proof. Let be an orthogonal matrix whose first row is ; one exists because a unit vector can be completed to an orthonormal basis (Gram-Schmidt). Let , a vector of iid variables, with density . Let . The map has Jacobian and keeps , so has the same density: are iid . Now . Also , so . So is a function of alone, and of alone, which makes them independent. gives the law of , and a sum of squares of iid standard normals is by definition.
Lemma 2 (the one-sample null law). Under the model of Lemma 1, has the law of with , independent, and . In particular when , whatever is.
Proof. Divide the numerator and the denominator by : with and . By Lemma 1, and are independent and . At , , and the law is by definition. has cancelled.
Lemma 3 (paired data). If the pairs are iid and , then the paired statistic is the one-sample statistic of with , and it is under .
Proof. The code forms and calls the one-sample test, and the are iid , so Lemma 2 applies. This holds in particular when each pair is bivariate normal, whatever the correlation in the pair.
Lemma 4 (the pooled null law). Let be iid and iid , independent, with the same , and . Let , where is the sum of squared deviations from the sample's own mean. Then when .
Proof. By Lemma 1 applied to each sample (for a sample of size 1, and the claims about hold trivially), , , , are independent, with and (where is the point mass at 0). A sum of independent chi-square variables is chi-square with the summed degrees of freedom (multiply their moment generating functions ), so . Also , independent of . Under , with .
The common is used twice: it makes chi-square, and it makes the same cancel from and . With , is a weighted sum of two chi-square variables, is not , and its law depends on .
Lemma 5 (p-values and size). Let be the CDF of and . The code returns ("greater"), ("less") and (two-sided). Under a null where , each p-value satisfies for , so rejecting when has size exactly .
Proof. The law is symmetric about 0 (because is) and has a positive density on the real line, so is continuous and strictly increasing, and . The p-values are the probabilities of , and . Uniformity follows as for any continuous statistic: has probability , and has probability . The helper function t_sf computes for , the standard identity for the t tail through the regularized incomplete beta function.
Lemma 6 (the composite one-sided null). For , the rule "reject when " has size exactly .
Proof. By Lemma 2, . For each fixed value of , the event grows with , so by independence and averaging over the probability is nondecreasing in , which increases with . Its supremum over and all is its value at , which is .
Lemma 7 (without normality). Let be iid with mean and variance , of any shape. Then converges in distribution to , and the size of each rule tends to .
Proof. By the central limit theorem, converges in distribution to . By the law of large numbers, and in probability, so in probability, and in probability by continuity. Slutsky's theorem (a product with a factor that converges in probability to a constant) gives in distribution. The critical values tend to , because in probability for . The limit law is continuous, so the rejection probabilities tend to .
Termination. The one-sample test makes two passes over numbers and a constant number of further operations. The p-value calls the incomplete beta continued fraction, which stops when a step changes the value by a relative amount below or after a fixed cap of iterations. So the test stops after arithmetic operations plus a bounded number of iterations.
Theorem. Under iid normal data, Student's one-sample and paired tests return with under , the pooled test returns under when the two variances are equal, and the p-values give tests of size exactly for every sample size. Without normality, for iid data with finite positive variance, the one-sample size tends to .
Proof. Lemmas 1 to 6 for the exact claims, and Lemma 7 for the limit.
Complexity
On a real RAM, lines L2 and L3 make two passes: additions and a division for the mean, then subtractions, squarings and additions for the sum of squares. So the time is , about arithmetic operations, and the extra space is besides the stored data. The tail costs a number of continued fraction steps that does not grow with for the values that matter. The pooled test is .
Numerical stability. The one-pass formula subtracts two nearly equal numbers when the mean is large compared with the spread, which is catastrophic cancellation. For the values , whose is 30, it returns 0 in double precision, and with in place of it returns 21845.3. A variance of 0 makes infinite. Line L3 uses the two-pass formula, which subtracts the mean first. For data that arrive one at a time, the Welford algorithm gives the same accuracy in one pass. The p-value uses the upper tail directly, so a p-value of is not rounded to 0.
Properties
- Exact under normality. Size for every and every : the test is similar on the boundary of the null.
- Invariant. does not change when all data and are shifted together or scaled by a positive factor.
- Optimal. The two-sided t-test is the likelihood ratio test for with unknown, and both the one- and two-sided forms are uniformly most powerful unbiased (Lehmann and Romano, Section 5.2).
- Robust in level, not in power. For symmetric non-normal data the two-sided size stays close to even for moderate . For skewed data the one-sided sizes are off, as the table shows. Heavy tails make large and the power low.
- Dual to an interval. The two-sided test at level fails to reject exactly when lies in the t confidence interval . For the sleep data this is , which excludes 0.
Variants and improvements
- Welch's t-test. Drops the equal variance assumption for two samples. It is approximate, but its size stays near where the pooled test fails. Many texts now use it as the default two-sample test.
- Rank tests. The Wilcoxon signed-rank test (one-sample or paired) and the Mann-Whitney U test (two samples) have exact null laws for continuous data without normality: the first needs a distribution symmetric about the null value, the second two samples from the same distribution.
- Permutation test. Uses the t statistic but takes its null distribution from the permutations or sign flips of the data, which is exact under exchangeability.
- More than two groups. One-way ANOVA generalizes the pooled test: with two groups, its F statistic is .
- Equivalence testing. Two one-sided t-tests (TOST) show that a mean lies within a margin, which a non-significant t-test cannot show.
When to use it
Use the one-sample or paired t-test for a mean when is unknown and the data, or the differences, are close to normal, or when is large and the data are not strongly skewed. Use the paired form whenever the two measurements come from the same unit. For two independent groups, use the pooled form only when the variances are known to be equal or the group sizes are equal; otherwise use the Welch t-test. For small samples from a clearly skewed or heavy-tailed population, use a rank or permutation test.
Pitfalls
- Pooling with unequal variances and unequal sizes. The size can be 0.30 instead of 0.05 (table above). Equal sizes protect the level; equal variances are rarely known.
- Ignoring the pairing. The pooled analysis of paired data includes the between-unit variation, and the sleep data lose their significance.
- Pairing independent samples. The paired test on two independent groups of equal size, matched by position, throws away degrees of freedom and depends on an arbitrary order.
- Using critical values. With , has null probability 0.122, not 0.05.
- Reading the asymptotic claim as exact. Outside normality the t-test is asymptotic only: for exponential data with the "less" size is 0.155.
- Testing for normality first and then choosing the test. The two-stage procedure does not have the nominal size, and a normality test has little power at the small where it matters.
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)
student_t_core.py 76 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/student-t-test/. The authors are listed in prov/M2JJ9R.jsonl.
"""Student's one-sample, paired and pooled two-sample t-tests.
Each function returns (t, df, p): the statistic, its degrees of freedom and
the p-value for the alternative "two-sided", "greater" (H_1: parameter >
null value) or "less". S^2 uses the divisor n - 1 and the two-pass formula,
which does not cancel like sum x^2 - n xbar^2. Tail areas come from the
upper tail t_sf directly, not from 1 - cdf. The code is in this file and not
in student_t_test.py, because tools treat a file whose name ends in _test.py
as a test file.
"""
import math
from collections.abc import Sequence
from stdist import t_sf
ALTERNATIVES = ("two-sided", "greater", "less")
def t_p_value(t: float, df: float, alternative: str = "two-sided") -> float:
"""The p-value of an observed t when T has the t distribution with df degrees of freedom."""
if alternative == "two-sided":
return min(1.0, 2.0 * t_sf(abs(t), df)) # @line L7
if alternative == "greater":
return t_sf(t, df) # @line L8
if alternative == "less":
return t_sf(-t, df) # @line L9
raise ValueError(f"alternative must be one of {ALTERNATIVES}")
def mean_and_ss(x: Sequence[float]) -> tuple[float, float]:
"""The mean and the sum of squared deviations, by two passes."""
n = len(x)
mean = math.fsum(x) / n
return mean, math.fsum((v - mean) ** 2 for v in x)
def one_sample_t_test(x: Sequence[float], mu0: float = 0.0,
alternative: str = "two-sided") -> tuple[float, int, float]:
"""Test H_0: mu = mu0 for iid N(mu, sigma^2) data with sigma unknown."""
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
if s2 == 0.0:
raise ValueError("all observations are equal, so S = 0 and t is undefined")
t = (mean - mu0) / math.sqrt(s2 / n) # @line L4
df = n - 1 # @line L5
return t, df, t_p_value(t, df, alternative) # @line L6
def paired_t_test(x: Sequence[float], y: Sequence[float], delta0: float = 0.0,
alternative: str = "two-sided") -> tuple[float, int, float]:
"""Test H_0: E[X - Y] = delta0 from pairs (x_i, y_i): the one-sample test on x_i - y_i."""
if len(x) != len(y):
raise ValueError("paired samples must have the same length")
return one_sample_t_test([a - b for a, b in zip(x, y)], delta0, alternative)
def pooled_t_test(x: Sequence[float], y: Sequence[float], delta0: float = 0.0,
alternative: str = "two-sided") -> tuple[float, int, float]:
"""Test H_0: mu_x - mu_y = delta0 for independent normal samples with a common variance."""
m, n = len(x), len(y)
if m < 1 or n < 1 or m + n < 3:
raise ValueError("need m, n >= 1 and m + n >= 3")
mx, ssx = mean_and_ss(x)
my, ssy = mean_and_ss(y)
df = m + n - 2
sp2 = (ssx + ssy) / df # pooled S^2 with divisor m + n - 2
if sp2 == 0.0:
raise ValueError("both samples are constant, so the pooled S = 0")
t = (mx - my - delta0) / math.sqrt(sp2 * (1.0 / m + 1.0 / n))
return t, df, t_p_value(t, df, alternative)
student_t_test.py 11 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/student-t-test/. The authors are listed in prov/M2JJ9R.jsonl.
"""Entry point named after the slug. The code lives in student_t_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""
from student_t_core import (
ALTERNATIVES, mean_and_ss, one_sample_t_test, paired_t_test, pooled_t_test, t_p_value,
)
__all__ = ["ALTERNATIVES", "mean_and_ss", "one_sample_t_test", "paired_t_test", "pooled_t_test",
"t_p_value"]
test_stdist.py 73 lines
# SPDX-License-Identifier: MIT
# Shared helper of the statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
import math
from stdist import (
beta_inc, chi2_cdf, chi2_ppf, chi2_sf, f_cdf, f_ppf, f_sf, gamma_p, gamma_q,
norm_cdf, norm_ppf, norm_sf, t_cdf, t_ppf, t_sf,
)
XS = [0.001, 0.01, 0.1, 0.3, 0.5, 1.0, 1.7, 2.5, 4.0, 7.0, 12.0, 30.0, 80.0]
def test_chi2_two_degrees_of_freedom() -> None:
for x in XS:
assert abs(chi2_cdf(x, 2) - (1.0 - math.exp(-x / 2.0))) < 1e-13
assert abs(chi2_sf(x, 2) - math.exp(-x / 2.0)) <= 1e-12 * math.exp(-x / 2.0)
def test_t_one_and_two_degrees_of_freedom() -> None:
for x in XS + [-v for v in XS] + [0.0]:
assert abs(t_cdf(x, 1) - (0.5 + math.atan(x) / math.pi)) < 1e-13
assert abs(t_cdf(x, 2) - (0.5 + x / (2.0 * math.sqrt(2.0 + x * x)))) < 1e-13
assert abs(t_cdf(x, 3) + t_sf(x, 3) - 1.0) < 1e-14
def test_t_upper_tail_one_degree_of_freedom_is_relatively_accurate() -> None:
# P(T > x) = atan(1/x)/pi for x > 0 and one degree of freedom.
for x in [10.0, 1e3, 1e6]:
exact = math.atan(1.0 / x) / math.pi
assert abs(t_sf(x, 1) / exact - 1.0) < 1e-12
def test_t_tends_to_normal() -> None:
for x in [-2.0, -0.5, 0.7, 1.96, 3.0]:
assert abs(t_cdf(x, 1e7) - norm_cdf(x)) < 1e-6
def test_f_is_square_of_t() -> None:
for k in [1, 2, 3, 5, 10, 30]:
for x in XS:
two_sided = 2.0 * t_sf(math.sqrt(x), k)
assert abs(f_sf(x, 1, k) - two_sided) < 1e-13
assert abs(f_cdf(x, 1, k) + f_sf(x, 1, k) - 1.0) < 1e-14
def test_gamma_and_beta_identities() -> None:
for a in [0.5, 1.0, 2.5, 10.0, 50.0]:
for x in XS:
assert abs(gamma_p(a, x) + gamma_q(a, x) - 1.0) < 1e-14
# P(1, x) = 1 - e^(-x); I_x(a, 1) = x^a; I_x(1, b) = 1 - (1 - x)^b.
for x in [0.05, 0.3, 0.5, 0.8, 0.99]:
assert abs(gamma_p(1.0, x) - (1.0 - math.exp(-x))) < 1e-14
for a in [0.5, 2.0, 7.0]:
assert abs(beta_inc(a, 1.0, x) - x**a) < 1e-13
assert abs(beta_inc(1.0, a, x) - (1.0 - (1.0 - x) ** a)) < 1e-13
def test_upper_tails_do_not_cancel() -> None:
assert abs(norm_sf(10.0) / 7.619853024160527e-24 - 1.0) < 1e-12
assert abs(chi2_sf(200.0, 2) / math.exp(-100.0) - 1.0) < 1e-12
assert norm_cdf(-30.0) > 0.0
def test_quantiles() -> None:
assert abs(norm_ppf(0.975) - 1.959963985) < 1e-8
assert abs(chi2_ppf(0.95, 1) - 3.841458821) < 1e-8
assert abs(t_ppf(0.975, 10) - 2.228138852) < 1e-8
for p in [1e-6, 0.01, 0.2, 0.5, 0.8, 0.99, 1.0 - 1e-6]:
for k in [1, 4, 25]:
assert abs(chi2_cdf(chi2_ppf(p, k), k) - p) < 1e-12
assert abs(t_cdf(t_ppf(p, k), k) - p) < 1e-12
assert abs(f_cdf(f_ppf(p, k, 7), k, 7) - p) < 1e-12
test_student_t_test.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/student-t-test/. The authors are listed in prov/M2JJ9R.jsonl.
import math
import random
from fractions import Fraction
import pytest
from student_t_test import one_sample_t_test, paired_t_test, pooled_t_test, t_p_value
# Cushny and Peebles (1905), as used by Student (1908): extra hours of sleep under two drugs.
DRUG_1 = [0.7, -1.6, -0.2, -1.2, -0.1, 3.4, 3.7, 0.8, 0.0, 2.0]
DRUG_2 = [1.9, 0.8, 1.1, 0.1, -0.1, 4.4, 5.5, 1.6, 4.6, 3.4]
def exact_t_squared(x: list[Fraction], mu0: Fraction) -> Fraction:
"""t^2 = n (xbar - mu0)^2 / S^2 with S^2 = sum (x_i - xbar)^2 / (n - 1), in exact arithmetic."""
n = len(x)
mean = sum(x, Fraction(0)) / n
s2 = sum(((v - mean) ** 2 for v in x), Fraction(0)) / (n - 1)
return n * (mean - mu0) ** 2 / s2
def test_sleep_data_paired() -> None:
t, df, p = paired_t_test(DRUG_2, DRUG_1)
d = [Fraction(b).limit_denominator(10) - Fraction(a).limit_denominator(10)
for a, b in zip(DRUG_1, DRUG_2)]
assert df == 9
assert abs(t * t - float(exact_t_squared(d, Fraction(0)))) < 1e-9
assert abs(t - 4.062127683382037) < 1e-9
assert abs(p - 0.0028328901973842632) < 1e-9
assert abs(paired_t_test(DRUG_2, DRUG_1, alternative="greater")[2] - p / 2.0) < 1e-15
def test_paired_is_one_sample_on_differences() -> None:
rng = random.Random(3)
for _ in range(20):
n = rng.randint(2, 15)
x = [rng.gauss(0.0, 1.0) for _ in range(n)]
y = [v + rng.gauss(0.3, 0.5) for v in x]
for alt in ("two-sided", "greater", "less"):
assert paired_t_test(x, y, 0.1, alt) == one_sample_t_test(
[a - b for a, b in zip(x, y)], 0.1, alt)
def test_statistic_against_fractions() -> None:
rng = random.Random(8)
for _ in range(60):
n = rng.randint(2, 12)
x = [rng.randint(-20, 20) for _ in range(n)]
if len(set(x)) == 1:
continue
mu0 = rng.randint(-3, 3)
t, df, _ = one_sample_t_test(x, mu0)
assert df == n - 1
exact = exact_t_squared([Fraction(v) for v in x], Fraction(mu0))
assert abs(t * t - float(exact)) <= 1e-12 * max(1.0, float(exact))
def test_pooled_against_fractions() -> None:
rng = random.Random(9)
for _ in range(40):
m, n = rng.randint(1, 8), rng.randint(2, 8)
x = [Fraction(rng.randint(-9, 9)) for _ in range(m)]
y = [Fraction(rng.randint(-9, 9)) for _ in range(n)]
mx, my = sum(x) / m, sum(y) / n
sp2 = (sum((v - mx) ** 2 for v in x) + sum((v - my) ** 2 for v in y)) / (m + n - 2)
if sp2 == 0:
continue
t2 = (mx - my) ** 2 / (sp2 * (Fraction(1, m) + Fraction(1, n)))
t, df, _ = pooled_t_test([float(v) for v in x], [float(v) for v in y])
assert df == m + n - 2
assert abs(t * t - float(t2)) <= 1e-12 * max(1.0, float(t2))
def test_two_observations_give_the_cauchy_law() -> None:
# With n = 2 the null law is t with 1 degree of freedom: P(|T| >= t) = 1 - 2 atan(t) / pi.
for x in ([0.0, 1.0], [3.0, 3.5], [-2.0, 5.0], [1.0, 1.001]):
t, df, p = one_sample_t_test(x, 0.0)
assert df == 1
assert abs(p - (1.0 - 2.0 * math.atan(abs(t)) / math.pi)) < 1e-12
def test_small_p_value_is_not_zero() -> None:
# P(T_30 > 20) is about 1e-19; 1 - cdf would round it to 0.
p = t_p_value(20.0, 30, "greater")
assert 0.0 < p < 1e-17
assert t_p_value(0.0, 5) == 1.0
def null_size(n: int, alternative: str, r: int, seed: int) -> float:
rng = random.Random(seed)
hits = 0
for _ in range(r):
hits += one_sample_t_test([rng.gauss(10.0, 3.0) for _ in range(n)], 10.0, alternative)[2] <= 0.05
return hits / r
@pytest.mark.parametrize("n,alternative,seed", [(3, "two-sided", 1), (5, "greater", 2), (12, "less", 3)])
def test_monte_carlo_size_is_alpha_under_normality(n: int, alternative: str, seed: int) -> None:
r = 4000
assert abs(null_size(n, alternative, r, seed) - 0.05) < 4.0 * math.sqrt(0.05 * 0.95 / r)
def test_p_values_are_uniform_under_the_null() -> None:
rng = random.Random(21)
r = 3000
ps = [one_sample_t_test([rng.gauss(0.0, 1.0) for _ in range(4)])[2] for _ in range(r)]
for u in (0.1, 0.3, 0.5, 0.8):
assert abs(sum(p <= u for p in ps) / r - u) < 4.0 * math.sqrt(u * (1.0 - u) / r)
def pooled_size(m: int, sd_x: float, n: int, sd_y: float, r: int, seed: int) -> float:
rng = random.Random(seed)
hits = 0
for _ in range(r):
x = [rng.gauss(0.0, sd_x) for _ in range(m)]
y = [rng.gauss(0.0, sd_y) for _ in range(n)]
hits += pooled_t_test(x, y)[2] <= 0.05
return hits / r
def test_pooled_size_is_alpha_with_equal_variances() -> None:
r = 4000
assert abs(pooled_size(5, 2.0, 25, 2.0, r, 4) - 0.05) < 4.0 * math.sqrt(0.05 * 0.95 / r)
def test_pooled_test_fails_with_unequal_variances_and_sizes() -> None:
# The small sample is the noisy one: the pooled S^2 is dominated by the quiet large sample,
# the standard error is too small, and the test rejects a true null far too often.
r = 4000
size = pooled_size(5, 3.0, 25, 1.0, r, 5)
assert size > 0.05 + 4.0 * math.sqrt(0.05 * 0.95 / r)
assert size > 0.2
# The large sample is the noisy one: the test almost never rejects.
assert pooled_size(5, 1.0, 25, 3.0, r, 6) < 0.01
def test_bad_input() -> None:
with pytest.raises(ValueError):
one_sample_t_test([1.0])
with pytest.raises(ValueError):
one_sample_t_test([2.0, 2.0, 2.0])
with pytest.raises(ValueError):
paired_t_test([1.0, 2.0], [1.0])
with pytest.raises(ValueError):
t_p_value(1.0, 3, "both")
History
William Sealy Gosset, a chemist and brewer at Guinness in Dublin, published "The probable error of a mean" in Biometrika in 1908 under the name Student. He derived the law of the mean divided by the sample standard deviation for normal samples, checked it with a sampling experiment on measurements written on cards, and applied it to the Cushny and Peebles sleep data. Student's statistic was , with computed with the divisor . Fisher gave a full derivation, wrote the statistic as with the divisor , and extended it to the comparison of two means and to regression coefficients in Statistical Methods for Research Workers (1925).
References
- 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, its table, and the sleep data of Cushny and Peebles as the worked example)
- George Casella and Roger L. Berger, Statistical Inference, second edition, Duxbury, 2002, Section 5.3 (sampling from the normal distribution, the independence of X-bar and S^2, Student's t) and Chapter 8 (the one-sample t-test as a likelihood ratio test, its size and power)
- E. L. Lehmann and Joseph P. Romano, Testing Statistical Hypotheses, third edition, Springer, 2005, Section 5.2 (testing the parameters of a normal distribution, the one-sample t-test as UMP unbiased) and Chapter 5 (the two-sample and paired comparisons)
- Ronald A. Fisher, Statistical Methods for Research Workers, Oliver and Boyd, 1925, online text of the first edition, Chapter V (tests of significance of means, differences of means and regression coefficients)
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 M2JJ9R Edit this page History Report an error Markdown