Algorithm Search⌘K

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
Properties
deterministicexactofflineiterative
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 S2S^2 with divisor n−1n - 1. Under iid normal data, the statistic has the t distribution with n−1n - 1 degrees of freedom exactly, for every n≥2n \ge 2, so the test has size exactly α\alpha. 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. X1,…,XnX_1, \dots, X_n are iid N(μ,σ2)N(\mu, \sigma^2) with both μ\mu and σ\sigma unknown, n≥2n \ge 2. H0:μ=μ0H_0: \mu = \mu_0 against H1:μ≠μ0H_1: \mu \ne \mu_0 (two-sided), μ>μ0\mu > \mu_0 ("greater") or μ<μ0\mu < \mu_0 ("less"); for a one-sided alternative the null may be the composite μ≤μ0\mu \le \mu_0 or μ≥μ0\mu \ge \mu_0. The standard deviation σ\sigma is a nuisance parameter.

Statistic. With Xˉ=1n∑Xi\bar X = \frac1n\sum X_i and S2=1n−1∑(Xi−Xˉ)2S^2 = \frac{1}{n-1}\sum (X_i - \bar X)^2 (divisor n−1n - 1),

T=Xˉ−μ0S/n.T = \frac{\bar X - \mu_0}{S/\sqrt n}.

Null distribution. Exact: T∼tn−1T \sim t_{n-1} under H0H_0, whatever σ\sigma is. The reason is that Xˉ\bar X and S2S^2 are independent under normality, and (n−1)S2/σ2(n - 1)S^2/\sigma^2 is chi-square with n−1n - 1 degrees of freedom. Without normality, for iid data with finite variance, TT converges in distribution to N(0,1)N(0, 1) by the central limit theorem and Slutsky's theorem, so the test is only asymptotic.

Rejection rule and size. With the lower quantile t(n−1,p)t_{(n-1, p)}: reject when ∣T∣≥t(n−1,1−α/2)|T| \ge t_{(n-1, 1-\alpha/2)} (two-sided), T≥t(n−1,1−α)T \ge t_{(n-1, 1-\alpha)} ("greater") or T≤−t(n−1,1−α)T \le -t_{(n-1, 1-\alpha)} ("less"). Under normality the size equals α\alpha, also for the composite one-sided null. For α=0.05\alpha = 0.05 two-sided, t(4,0.975)=2.776445t_{(4, 0.975)} = 2.776445, t(9,0.975)=2.262157t_{(9, 0.975)} = 2.262157, t(30,0.975)=2.042272t_{(30, 0.975)} = 2.042272, and the limit is z0.975=1.959964z_{0.975} = 1.959964.

p-value. With Fˉν(t)=P(Tν>t)\bar F_\nu(t) = P(T_\nu > t) the upper tail of tνt_\nu: p=Fˉn−1(t)p = \bar F_{n-1}(t) ("greater"), Fˉn−1(−t)\bar F_{n-1}(-t) ("less") and 2Fˉn−1(∣t∣)2\bar F_{n-1}(|t|) (two-sided). The null law is symmetric, so doubling and the "no more likely" rule agree.

Paired test. Pairs (Xi,Yi)(X_i, Y_i), iid over ii, measured on the same unit. With Di=Xi−YiD_i = X_i - Y_i iid N(δ,σD2)N(\delta, \sigma_D^2), test H0:δ=δ0H_0: \delta = \delta_0 by the one-sample test on D1,…,DnD_1, \dots, D_n, with n−1n - 1 degrees of freedom. The pairs may be correlated; only the differences must be iid normal.

Pooled two-sample test. X1,…,XmX_1, \dots, X_m iid N(μX,σ2)N(\mu_X, \sigma^2) and Y1,…,YnY_1, \dots, Y_n iid N(μY,σ2)N(\mu_Y, \sigma^2), independent, with the same σ\sigma. With Sp2=(∑(Xi−Xˉ)2+∑(Yj−Yˉ)2)/(m+n−2)S_p^2 = \big(\sum (X_i - \bar X)^2 + \sum (Y_j - \bar Y)^2\big)/(m + n - 2) (divisor m+n−2m + n - 2),

T=Xˉ−Yˉ−δ0Sp1/m+1/n∼tm+n−2under H0:μX−μY=δ0.T = \frac{\bar X - \bar Y - \delta_0}{S_p\sqrt{1/m + 1/n}} \sim t_{m+n-2} \quad \text{under } H_0: \mu_X - \mu_Y = \delta_0 .

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 μ\mu and σ\sigma only through λ=n(μ−μ0)/σ\lambda = \sqrt n(\mu - \mu_0)/\sigma: TT then has the noncentral t law with n−1n - 1 degrees of freedom and noncentrality λ\lambda. With 10 observations at α=0.05\alpha = 0.05 two-sided, the power is 0.293 at λ/n=0.5\lambda/\sqrt n = 0.5 and 0.803 at λ/n=1\lambda/\sqrt n = 1, against 0.353 and 0.885 for the z-test with σ\sigma known. That gap is the price of estimating σ\sigma. 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

  1. STUDENT-T-TEST(x[1..n], μ₀, alternative) ▷ 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. 4t ← (x̄ − μ₀) / √(S² / n)
  6. 5ν ← n − 1
  7. 6return (t, ν, T-P-VALUE(t, ν, alternative))
  8. T-P-VALUE(t, ν, alternative)
  9. 7if alternative = two-sided then return min(1, 2 · F̄_ν(|t|))
  10. 8if alternative = greater then return F̄_ν(t)
  11. 9if alternative = less then return F̄_ν(−t)

The upper tail is Fˉν(t)=12Iν/(ν+t2)(ν/2,1/2)\bar F_\nu(t) = \tfrac12 I_{\nu/(\nu + t^2)}(\nu/2, 1/2) for t≥0t \ge 0, where Ix(a,b)I_x(a, b) is the regularized incomplete beta function. The helper evaluates it by its continued fraction, so a tail of 10−1910^{-19} keeps its digits. The paired test calls STUDENT-T-TEST on xi−yix_i - y_i. The pooled test computes both means and both sums of squared deviations by two passes, forms Sp2S_p^2, and calls T-P-VALUE with ν=m+n−2\nu = m + n - 2. If S=0S = 0 (all values equal), tt 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

1.2, 2.4, 1.3, 1.3, 0.0, 1.0, 1.8, 0.8, 4.6, 1.4.1.2,\ 2.4,\ 1.3,\ 1.3,\ 0.0,\ 1.0,\ 1.8,\ 0.8,\ 4.6,\ 1.4 .

Test H0:δ=0H_0: \delta = 0 against H1:δ≠0H_1: \delta \ne 0 at α=0.05\alpha = 0.05.

line value
L2: dˉ=15.8/10\bar d = 15.8/10 1.581.58
L3: ∑(di−dˉ)2\sum (d_i - \bar d)^2 13.61613.616
L3: S2=13.616/9S^2 = 13.616/9 1.5128891.512889
L4: S/10S/\sqrt{10} 0.3889590.388959
L4: t=1.58/0.388959t = 1.58/0.388959 4.06214.0621
L5: ν\nu 99
L7: p=2Fˉ9(4.0621)p = 2\bar F_9(4.0621) 0.0028330.002833

Since 4.0621≥t(9,0.975)=2.2621574.0621 \ge t_{(9, 0.975)} = 2.262157, the test rejects H0H_0; the second drug gave more sleep. The one-sided p-value for H1:δ>0H_1: \delta > 0 is 0.0014160.001416.

Ignoring the pairing. Treat the same 20 numbers as two independent groups of 10 and run the pooled test. Then t=1.8608t = 1.8608 with ν=18\nu = 18 and p=0.0792p = 0.0792: 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 r=4000r = 4000 replications at level 0.05 (standard error of an estimated size near 0.05: 0.0034):

data test measured size seed
normal, n=5n = 5 one-sample, two-sided 0.0478 1
exponential with mean 1, n=5n = 5 one-sample, two-sided 0.1235 2
exponential with mean 1, n=5n = 5 one-sample, "greater" / "less" 0.0115 / 0.1553 2
exponential with mean 1, n=30n = 30 one-sample, two-sided 0.0800 3
normal, σX=σY=1\sigma_X = \sigma_Y = 1, m=5m = 5, n=25n = 25 pooled 0.0505 4
normal, σX=3\sigma_X = 3, σY=1\sigma_Y = 1, m=5m = 5, n=25n = 25 pooled 0.3000 5
normal, σX=1\sigma_X = 1, σY=3\sigma_Y = 3, m=5m = 5, n=25n = 25 pooled 0.0015 6
normal, σX=3\sigma_X = 3, σY=1\sigma_Y = 1, m=n=15m = n = 15 pooled 0.0593 7

The exponential rows show that skewness spoils the one-sided sizes in opposite directions and that n=30n = 30 is not yet "large". The pooled rows show the failure with unequal variances and unequal sizes. When the small group is the noisy one, Sp2S_p^2 is dominated by the quiet large group. Its expectation is (4⋅9+24⋅1)/28=2.143(4 \cdot 9 + 24 \cdot 1)/28 = 2.143, so the estimated variance of Xˉ−Yˉ\bar X - \bar Y is about 2.143×0.24=0.5142.143 \times 0.24 = 0.514, while the true variance is 9/5+1/25=1.849/5 + 1/25 = 1.84. The standard error is too small by a factor 3.58=1.89\sqrt{3.58} = 1.89, and P(∣Z∣≥1.96/1.89)=0.300P(|Z| \ge 1.96/1.89) = 0.300, 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 n Xˉ\sqrt n\,\bar X turns the sample into nn independent normal coordinates. Xˉ\bar X depends only on the first, and (n−1)S2/σ2(n - 1)S^2/\sigma^2 is the sum of squares of the other n−1n - 1 standardized coordinates. So the two are independent, the second is chi-square with n−1n - 1 degrees of freedom, and TT is a standard normal over the root of an independent chi-square divided by its degrees of freedom, which is the definition of tn−1t_{n-1}. The unknown σ\sigma 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 H0H_0 and the size is exactly α\alpha. Without normality, S→σS \to \sigma 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 α\alpha, and that without normality the size tends to α\alpha. Write tνt_{\nu} for the t distribution with ν\nu degrees of freedom: the law of Z/V/νZ/\sqrt{V/\nu} where Z∼N(0,1)Z \sim N(0, 1) and V∼χν2V \sim \chi^2_\nu are independent. S2S^2 always has the divisor n−1n - 1.

Lemma 1 (Helmert's transformation). Let X1,…,XnX_1, \dots, X_n be iid N(μ,σ2)N(\mu, \sigma^2), n≥2n \ge 2. Then Xˉ\bar X and S2=1n−1∑(Xi−Xˉ)2S^2 = \frac{1}{n-1}\sum (X_i - \bar X)^2 are independent, Xˉ∼N(μ,σ2/n)\bar X \sim N(\mu, \sigma^2/n), and (n−1)S2/σ2∼χn−12(n - 1)S^2/\sigma^2 \sim \chi^2_{n-1}.

Proof. Let HH be an orthogonal n×nn \times n matrix whose first row is (1/n,…,1/n)(1/\sqrt n, \dots, 1/\sqrt n); one exists because a unit vector can be completed to an orthonormal basis (Gram-Schmidt). Let W=(X−μ1)/σW = (X - \mu\mathbf 1)/\sigma, a vector of iid N(0,1)N(0, 1) variables, with density (2π)−n/2exp⁡(−∥w∥2/2)(2\pi)^{-n/2}\exp(-\|w\|^2/2). Let U=HWU = HW. The map w↦Hww \mapsto Hw has Jacobian ∣det⁡H∣=1|\det H| = 1 and keeps ∥w∥\|w\|, so UU has the same density: U1,…,UnU_1, \dots, U_n are iid N(0,1)N(0, 1). Now U1=n Wˉ=n(Xˉ−μ)/σU_1 = \sqrt n\,\bar W = \sqrt n(\bar X - \mu)/\sigma. Also ∑i=1nUi2=∥W∥2=∑Wi2\sum_{i=1}^n U_i^2 = \|W\|^2 = \sum W_i^2, so ∑i=2nUi2=∑Wi2−nWˉ2=∑(Wi−Wˉ)2=(n−1)S2/σ2\sum_{i=2}^n U_i^2 = \sum W_i^2 - n\bar W^2 = \sum (W_i - \bar W)^2 = (n - 1)S^2/\sigma^2. So Xˉ\bar X is a function of U1U_1 alone, and S2S^2 of U2,…,UnU_2, \dots, U_n alone, which makes them independent. U1∼N(0,1)U_1 \sim N(0, 1) gives the law of Xˉ\bar X, and a sum of n−1n - 1 squares of iid standard normals is χn−12\chi^2_{n-1} by definition. □\square

Lemma 2 (the one-sample null law). Under the model of Lemma 1, T=(Xˉ−μ0)/(S/n)T = (\bar X - \mu_0)/(S/\sqrt n) has the law of (Z+λ)/V/(n−1)(Z + \lambda)/\sqrt{V/(n-1)} with Z∼N(0,1)Z \sim N(0, 1), V∼χn−12V \sim \chi^2_{n-1} independent, and λ=n(μ−μ0)/σ\lambda = \sqrt n(\mu - \mu_0)/\sigma. In particular T∼tn−1T \sim t_{n-1} when μ=μ0\mu = \mu_0, whatever σ\sigma is.

Proof. Divide the numerator and the denominator by σ/n\sigma/\sqrt n: T=Z′/V/(n−1)T = Z'/\sqrt{V/(n-1)} with Z′=n(Xˉ−μ0)/σ∼N(λ,1)Z' = \sqrt n(\bar X - \mu_0)/\sigma \sim N(\lambda, 1) and V=(n−1)S2/σ2V = (n - 1)S^2/\sigma^2. By Lemma 1, Z′Z' and VV are independent and V∼χn−12V \sim \chi^2_{n-1}. At μ=μ0\mu = \mu_0, λ=0\lambda = 0, and the law is tn−1t_{n-1} by definition. σ\sigma has cancelled. □\square

Lemma 3 (paired data). If the pairs (Xi,Yi)(X_i, Y_i) are iid and Di=Xi−Yi∼N(δ,σD2)D_i = X_i - Y_i \sim N(\delta, \sigma_D^2), then the paired statistic is the one-sample statistic of D1,…,DnD_1, \dots, D_n with μ0=δ0\mu_0 = \delta_0, and it is tn−1t_{n-1} under H0:δ=δ0H_0: \delta = \delta_0.

Proof. The code forms di=xi−yid_i = x_i - y_i and calls the one-sample test, and the DiD_i are iid N(δ,σD2)N(\delta, \sigma_D^2), so Lemma 2 applies. This holds in particular when each pair is bivariate normal, whatever the correlation in the pair. □\square

Lemma 4 (the pooled null law). Let X1,…,XmX_1, \dots, X_m be iid N(μX,σ2)N(\mu_X, \sigma^2) and Y1,…,YnY_1, \dots, Y_n iid N(μY,σ2)N(\mu_Y, \sigma^2), independent, with the same σ\sigma, and m+n≥3m + n \ge 3. Let Sp2=(SSX+SSY)/(m+n−2)S_p^2 = (SS_X + SS_Y)/(m + n - 2), where SSSS is the sum of squared deviations from the sample's own mean. Then T=(Xˉ−Yˉ−δ0)/(Sp1/m+1/n)∼tm+n−2T = (\bar X - \bar Y - \delta_0)/(S_p\sqrt{1/m + 1/n}) \sim t_{m+n-2} when μX−μY=δ0\mu_X - \mu_Y = \delta_0.

Proof. By Lemma 1 applied to each sample (for a sample of size 1, SS=0SS = 0 and the claims about Xˉ\bar X hold trivially), Xˉ\bar X, SSXSS_X, Yˉ\bar Y, SSYSS_Y are independent, with SSX/σ2∼χm−12SS_X/\sigma^2 \sim \chi^2_{m-1} and SSY/σ2∼χn−12SS_Y/\sigma^2 \sim \chi^2_{n-1} (where χ02\chi^2_0 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 (1−2s)−k/2(1 - 2s)^{-k/2}), so V=(SSX+SSY)/σ2∼χm+n−22V = (SS_X + SS_Y)/\sigma^2 \sim \chi^2_{m+n-2}. Also Xˉ−Yˉ∼N(μX−μY,σ2(1/m+1/n))\bar X - \bar Y \sim N(\mu_X - \mu_Y, \sigma^2(1/m + 1/n)), independent of VV. Under H0H_0, T=Z/V/(m+n−2)T = Z/\sqrt{V/(m + n - 2)} with Z∼N(0,1)Z \sim N(0, 1). □\square

The common σ\sigma is used twice: it makes VV chi-square, and it makes the same σ\sigma cancel from ZZ and VV. With σX≠σY\sigma_X \ne \sigma_Y, (SSX+SSY)(SS_X + SS_Y) is a weighted sum of two chi-square variables, TT is not tt, and its law depends on σX/σY\sigma_X/\sigma_Y.

Lemma 5 (p-values and size). Let FνF_\nu be the CDF of tνt_\nu and Fˉν=1−Fν\bar F_\nu = 1 - F_\nu. The code returns Fˉν(t)\bar F_\nu(t) ("greater"), Fˉν(−t)=Fν(t)\bar F_\nu(-t) = F_\nu(t) ("less") and 2Fˉν(∣t∣)2\bar F_\nu(|t|) (two-sided). Under a null where T∼tνT \sim t_\nu, each p-value satisfies P(p≤u)=uP(p \le u) = u for u∈[0,1]u \in [0, 1], so rejecting when p≤αp \le \alpha has size exactly α\alpha.

Proof. The tνt_\nu law is symmetric about 0 (because ZZ is) and has a positive density on the real line, so FνF_\nu is continuous and strictly increasing, and Fˉν(−t)=Fν(t)\bar F_\nu(-t) = F_\nu(t). The p-values are the probabilities of {T≥t}\{T \ge t\}, {T≤t}\{T \le t\} and {∣T∣≥∣t∣}\{|T| \ge |t|\}. Uniformity follows as for any continuous statistic: {Fˉν(T)≤u}={T≥Fν−1(1−u)}\{\bar F_\nu(T) \le u\} = \{T \ge F_\nu^{-1}(1 - u)\} has probability uu, and {2Fˉν(∣T∣)≤u}={∣T∣≥Fν−1(1−u/2)}\{2\bar F_\nu(|T|) \le u\} = \{|T| \ge F_\nu^{-1}(1 - u/2)\} has probability uu. The helper function t_sf computes Fˉν(t)=12Iν/(ν+t2)(ν/2,1/2)\bar F_\nu(t) = \tfrac12 I_{\nu/(\nu + t^2)}(\nu/2, 1/2) for t≥0t \ge 0, the standard identity for the t tail through the regularized incomplete beta function. □\square

Lemma 6 (the composite one-sided null). For H0:μ≤μ0H_0: \mu \le \mu_0, the rule "reject when T≥Fn−1−1(1−α)T \ge F_{n-1}^{-1}(1 - \alpha)" has size exactly α\alpha.

Proof. By Lemma 2, Pμ,σ(T≥c)=P((Z+λ)/V/ν≥c)P_{\mu,\sigma}(T \ge c) = P((Z + \lambda)/\sqrt{V/\nu} \ge c). For each fixed value of VV, the event {Z≥cV/ν−λ}\{Z \ge c\sqrt{V/\nu} - \lambda\} grows with λ\lambda, so by independence and averaging over VV the probability is nondecreasing in λ\lambda, which increases with μ\mu. Its supremum over μ≤μ0\mu \le \mu_0 and all σ\sigma is its value at λ=0\lambda = 0, which is α\alpha. □\square

Lemma 7 (without normality). Let X1,…,XnX_1, \dots, X_n be iid with mean μ0\mu_0 and variance σ2∈(0,∞)\sigma^2 \in (0, \infty), of any shape. Then TT converges in distribution to N(0,1)N(0, 1), and the size of each rule tends to α\alpha.

Proof. By the central limit theorem, n(Xˉ−μ0)/σ\sqrt n(\bar X - \mu_0)/\sigma converges in distribution to N(0,1)N(0, 1). By the law of large numbers, 1n∑Xi2→σ2+μ02\frac1n\sum X_i^2 \to \sigma^2 + \mu_0^2 and Xˉ→μ0\bar X \to \mu_0 in probability, so S2=nn−1(1n∑Xi2−Xˉ2)→σ2S^2 = \frac{n}{n-1}(\frac1n\sum X_i^2 - \bar X^2) \to \sigma^2 in probability, and σ/S→1\sigma/S \to 1 in probability by continuity. Slutsky's theorem (a product with a factor that converges in probability to a constant) gives T=σS⋅n(Xˉ−μ0)σ→N(0,1)T = \frac{\sigma}{S}\cdot\frac{\sqrt n(\bar X - \mu_0)}{\sigma} \to N(0, 1) in distribution. The critical values Fn−1−1(1−α)F_{n-1}^{-1}(1 - \alpha) tend to z1−αz_{1-\alpha}, because V/ν→1V/\nu \to 1 in probability for V∼χν2V \sim \chi^2_\nu. The limit law is continuous, so the rejection probabilities tend to α\alpha. □\square

Termination. The one-sample test makes two passes over nn 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 10−1610^{-16} or after a fixed cap of iterations. So the test stops after O(n)O(n) arithmetic operations plus a bounded number of iterations.

Theorem. Under iid normal data, Student's one-sample and paired tests return TT with T∼tn−1T \sim t_{n-1} under H0H_0, the pooled test returns T∼tm+n−2T \sim t_{m+n-2} under H0H_0 when the two variances are equal, and the p-values give tests of size exactly α\alpha for every sample size. Without normality, for iid data with finite positive variance, the one-sample size tends to α\alpha.

Proof. Lemmas 1 to 6 for the exact claims, and Lemma 7 for the limit. ■\blacksquare

Complexity

On a real RAM, lines L2 and L3 make two passes: nn additions and a division for the mean, then nn subtractions, nn squarings and nn additions for the sum of squares. So the time is Θ(n)\Theta(n), about 4n4n arithmetic operations, and the extra space is Θ(1)\Theta(1) besides the stored data. The tail Fˉν\bar F_\nu costs a number of continued fraction steps that does not grow with nn for the values that matter. The pooled test is Θ(m+n)\Theta(m + n).

Numerical stability. The one-pass formula S2=(∑xi2−nxˉ2)/(n−1)S^2 = (\sum x_i^2 - n\bar x^2)/(n - 1) subtracts two nearly equal numbers when the mean is large compared with the spread, which is catastrophic cancellation. For the values 109+4,109+7,109+13,109+1610^9 + 4, 10^9 + 7, 10^9 + 13, 10^9 + 16, whose S2S^2 is 30, it returns 0 in double precision, and with 101010^{10} in place of 10910^9 it returns 21845.3. A variance of 0 makes tt 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 10−1910^{-19} is not rounded to 0.

Properties

  • Exact under normality. Size α\alpha for every n≥2n \ge 2 and every σ\sigma: the test is similar on the boundary of the null.
  • Invariant. TT does not change when all data and μ0\mu_0 are shifted together or scaled by a positive factor.
  • Optimal. The two-sided t-test is the likelihood ratio test for μ=μ0\mu = \mu_0 with σ\sigma 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 α\alpha even for moderate nn. For skewed data the one-sided sizes are off, as the table shows. Heavy tails make SS large and the power low.
  • Dual to an interval. The two-sided test at level α\alpha fails to reject μ0\mu_0 exactly when μ0\mu_0 lies in the t confidence interval Xˉ±t(n−1,1−α/2)S/n\bar X \pm t_{(n-1, 1-\alpha/2)}S/\sqrt n. For the sleep data this is [0.700,2.460][0.700, 2.460], 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 α\alpha 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 T2T^2.
  • 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 σ\sigma is unknown and the data, or the differences, are close to normal, or when nn 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 n−1n - 1 degrees of freedom and depends on an arbitrary order.
  • Using zz critical values. With n=5n = 5, ∣T∣≥1.96|T| \ge 1.96 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 n=5n = 5 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 nn 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.

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)
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 z=(xˉ−μ)/sz = (\bar x - \mu)/s, with ss computed with the divisor nn. Fisher gave a full derivation, wrote the statistic as tt with the divisor n−1n - 1, and extended it to the comparison of two means and to regression coefficients in Statistical Methods for Research Workers (1925).

References

  1. 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)
  2. 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)
  3. 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)
  4. 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.

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