Algorithmcore
Welch's t-test
Also called unequal variances t-test, Welch-Satterthwaite approximation.
Compares two normal means without assuming equal variances, using separate variance estimates and Welch-Satterthwaite degrees of freedom. Approximate, not exact. O(m + n).
- Time
- Θ(m + n) worst · best
- Space
- Θ(1) extra
- Where
- m = the size of the first sample; n = the size of the second sample
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Bernard Lewis Welch, Franklin E. Satterthwaite, 1947
Welch's t-test is a statistical hypothesis test for the difference of the means of two independent normal samples whose variances may differ. It divides the difference of the sample means by the square root of , where each sample variance has its own divisor or , and it refers the result to a t distribution with the Welch-Satterthwaite degrees of freedom, a real number between and . The test is approximate: its size is not exactly , but it stays close to in cases where the pooled Student t-test fails badly.
In plain words
You compare the averages of two separate groups, and the two groups may scatter by different amounts. The pooled t-test assumes equal scatter and mixes the two scatters into one. When the small group is the noisy one, that mixed value is too small, the test sees differences that are only noise, and it cries "significant" far too often. Welch's test keeps the two scatters apart and adds up the uncertainty of each average separately. The cost is that the exact law of the resulting count is unknown. Welch and Satterthwaite matched it to the closest t law, with a number of degrees of freedom computed from the data. The match is not perfect, but it is good in most practical cases.
The problem
Model and hypotheses. iid and iid , the two samples independent, , with unknown and allowed. against (two-sided), ("greater") or ("less"). The two variances are nuisance parameters. This is the Behrens-Fisher problem.
Statistic. With the means and the sample variances (divisors and ),
Null distribution. Approximate: under , is treated as . The numerator is exactly normal, but the denominator is the root of a weighted sum of two independent chi-square variables, which is not a scaled chi-square, and the exact law of depends on . The degrees of freedom match the first two moments of the denominator to those of a scaled chi-square (the Welch-Satterthwaite approximation, below). The law of tends to exactly when , and tends to as for any populations with finite variances, by the central limit theorem and Slutsky's theorem.
Rejection rule and size. Reject when (two-sided), ("greater") or ("less"), where is the lower quantile of for real . The size is close to but not equal to it; the table in the Example measures it.
p-value. With : ("greater"), ("less") and (two-sided). It is an approximate p-value: under it is only approximately uniform.
Sensitivity and power. The test reacts to a shift relative to . Its power is close to that of the pooled test when the variances are equal and the sizes are similar, and lower when one sample is very small, because is then small.
The algorithm
WELCH-T-TEST(x[1..m], y[1..n], δ₀, alternative) ▷ m, n ≥ 2- 1
(x̄, S²_X) ← the mean of x and its variance with divisor m − 1, by two passes - 2
(ȳ, S²_Y) ← the mean of y and its variance with divisor n − 1, by two passes - 3
a ← S²_X / m; b ← S²_Y / n - 4
t ← (x̄ − ȳ − δ₀) / √(a + b) - 5
ν ← (a + b)² / (a² / (m − 1) + b² / (n − 1)) - 6
return (t, ν, T-P-VALUE(t, ν, alternative))
T-P-VALUE is the procedure of Student's t-test: the upper tail of , doubled for the two-sided test. It works for real , because the shared helper evaluates by the continued fraction of the regularized incomplete beta function, which does not need an integer . If both samples are constant, and the code raises an error. If only one is constant, is the degrees of freedom of the other sample and the test is the one-sample t-test of that sample against the constant.
Example
Two independent groups: () and (). Test against at .
| line | value |
|---|---|
| L1: , , | , , |
| L2: , , | , , |
| L3: , | , |
| L4: | |
| L4: | |
| L5: | |
| L6: |
The critical value is , and , so the test does not reject. Almost all the uncertainty comes from the small noisy group, so is close to its . The dual 95% interval for is .
The pooled test on the same data uses (divisor ), the standard error , with 11 degrees of freedom and , and rejects. The quiet group of 8 dominates and makes the standard error too small; the table below shows that the pooled test rejects a true null far too often in exactly this situation.
Size under the model. Monte Carlo with replications at level 0.05, two-sided, normal data with equal means, seed 11, the same simulated data for both tests (standard error of an estimated size near 0.05: 0.0015):
| , | , | Welch size | pooled size |
|---|---|---|---|
| 5, 3 | 25, 1 | 0.0530 | 0.2998 |
| 5, 1 | 25, 3 | 0.0485 | 0.0012 |
| 5, 1 | 25, 1 | 0.0577 | 0.0505 |
| 3, 1 | 3, 1 | 0.0354 | 0.0508 |
| 3, 3 | 3, 1 | 0.0499 | 0.0734 |
| 2, 1 | 20, 1 | 0.1191 | 0.0475 |
| 2, 5 | 20, 1 | 0.0895 | 0.5489 |
| 10, 2 | 10, 1 | 0.0490 | 0.0529 |
| 4, 1 | 4, 10 | 0.0511 | 0.0855 |
Where the variances differ, the Welch size stays within 0.004 of 0.05 in every row with both sizes at least 3, while the pooled size ranges from 0.001 to 0.55. Where the variances are equal, the pooled test is exact and Welch is off: slightly with , conservative with , and badly with , where can be as low as 1 and its randomness matters most.
Correctness
Within each sample, the mean and the sample variance are independent (Helmert's transformation), so the numerator of is exactly normal and independent of the denominator. The denominator squared, with and , has mean and variance . A scaled chi-square with the same two moments has , and replacing the unknown variances by their estimates gives . Cauchy-Schwarz gives , with the top value exactly when . With , equals the pooled statistic. The size tends to when one variance tends to 0 (the test becomes the exact one-sample t-test of the other sample) and when . Nothing more is proved; between those limits the size is measured. The proofs are in the correctness proof below.
Proof: The Welch statistic, the Welch-Satterthwaite degrees of freedom, their bounds and the limits where the size is exactfull
We prove what is true of Welch's test and say plainly what is not. The test is approximate: we derive the degrees of freedom by moment matching, prove their bounds, prove that equal sample sizes give the pooled statistic, and prove that the size tends to in two limits. We do not prove that the size equals , because it does not. Throughout, are iid and are iid , independent of each other, with , and are unknown and may differ. and are the sample variances with divisors and . Write
and . The code returns , and the tail of .
Lemma 1 (the parts are independent). , , , and the three are independent.
Proof. Within one normal sample, the mean and the sample variance are independent, the mean is , and (size ) times the sample variance over is chi-square with size degrees of freedom. This is Helmert's transformation, Lemma 1 of the correctness proof of Student's t-test. The two samples are independent, so are four independent variables. is normal with mean and variance .
So under , with independent of . If were for some , would be exactly. It is not: with independent and , a weighted sum of two chi-square variables, whose law depends on the ratio .
Lemma 2 (the first two moments). and .
Proof. A variable has mean and variance (it is a sum of independent squares of standard normals, and , ). So has mean and variance , and the same for . and are independent, so the variances add.
Lemma 3 (Satterthwaite's moment matching). The scaled chi-square variable with the same mean and variance as has and .
Proof. has mean and variance . Matching the mean gives . Matching the variance gives by Lemma 2, so .
The unknown are replaced by their unbiased estimates , which gives , the value of welch_df. Both steps are approximations: the law of is not a scaled chi-square, and is random. Lemma 3 explains the formula; it does not give an exact null law.
Lemma 4 (bounds on ). For with , . The upper bound is an equality exactly when , and the lower bound is approached when the variance part of the smaller sample dominates.
Proof. Let and . Upper bound: by the Cauchy-Schwarz inequality for the vectors and ,
so , with equality exactly when the vectors are proportional, that is . Lower bound: let . Then , the last step because , so . If then , and if then ; so moves from the degrees of freedom of the sample that carries all the variance to when the two parts are balanced.
Lemma 5 (equal sample sizes). If , the Welch statistic equals the pooled statistic , and with equality exactly when .
Proof. With , , so , and the denominators agree. The claim on is Lemma 4 with : equality iff , that is .
So with equal sizes the two tests differ only in the degrees of freedom: the pooled test uses and Welch's test uses a data-dependent value at most .
Lemma 6 (one dominant variance: the size tends to exactly). Fix , and , and let . Under , the rejection probability of each of the three rules at level tends to . The same holds with the roles of the samples exchanged.
Proof. Write under . As , and both tend to 0 in probability, while the law of does not change. So, by Slutsky's theorem and the continuity of at , (and almost surely), converges in distribution to , the one-sample t statistic of the sample, which is by Lemma 2 of the Student proof. In the same way , jointly with . The p-value is a continuous function of for (the tail is continuous in both arguments), so by the continuous mapping theorem it converges in distribution to the tail of , which is uniform on (Lemma 5 of the Student proof). The uniform law is continuous at , so .
Lemma 7 (large samples: the size tends to ). Let be iid with mean and finite variance and iid with mean and finite variance , independent, of any shape. If (at any relative rate), then under the statistic converges in distribution to and the size of each rule tends to .
Proof. Let and , and , , so and under . By the central limit theorem, the characteristic functions of and of tend to , and by Lévy's continuity theorem the convergence is uniform for in compact sets. The weights stay in , so by independence the characteristic function of at is , which gives the limit. By the law of large numbers, and in probability, so in probability, and Slutsky's theorem gives in distribution. By Lemma 4, , so the critical values tend to the normal ones. The limit law is continuous, so the rejection probabilities tend to .
What is not proved. Between these limits the exact size of the Welch rule is a function of , and that is not constant and not equal to . This is the Behrens-Fisher problem. We do not prove a formula for it; the measurements on the page (for example a size of 0.119 at , , equal variances, , with replications and seed 11) show that it can differ from by much more than the Monte Carlo error.
Termination. Lines L1 and L2 make two passes over each sample, L3 to L5 are a constant number of operations, and the tail is the incomplete beta continued fraction of the shared helper, which stops after a fixed cap of iterations. So the test stops after arithmetic operations plus a bounded number of iterations.
Theorem. For independent normal samples, Welch's test returns and with . With its statistic is the pooled statistic. Its size tends to when one of the two variances tends to 0, and, for any populations with finite positive variances, when both sample sizes grow. Elsewhere it is an approximation whose error is measured, not bounded.
Proof. Lemmas 4 and 5 for the first two claims, Lemmas 6 and 7 for the limits, and Lemma 3 with the remark after Lemma 1 for the nature of the approximation.
Complexity
On a real RAM, lines L1 and L2 make two passes over each sample, about arithmetic operations, and L3 to L5 are a constant number of operations. So the time is and the extra space is besides the data. The tail costs a number of continued fraction steps that does not grow with or for the values that matter. The two-pass variances avoid the catastrophic cancellation of the one-pass formula, as on the Student page.
Properties
- Approximate. The size depends on , and the variance ratio, and in general differs from ; it tends to as one variance dominates or as both sizes grow.
- Degrees of freedom bounds. . is a random variable, not a fixed count.
- Same statistic as pooled at equal sizes. With the two statistics agree and only the degrees of freedom differ, . For the sleep data of Cushny and Peebles read as two groups of 10, for both, with and against 18 and .
- Invariant. and do not change when both samples and are shifted together, or when both samples are scaled by the same positive factor (with scaled too).
- Limited by the smaller sample. The quality of the approximation depends on the smaller sample: with the size can be more than twice .
Variants and improvements
- Welch-Satterthwaite approximation in general. For a combination of independent variance estimates with degrees of freedom each, the effective degrees of freedom are . The two-sample test is the case , . The same formula gives approximate degrees of freedom in mixed-effects models and for combined measurement uncertainties.
- Welch interval. By test-interval duality, is an approximate interval for ; its coverage error is the size error of the test.
- Conservative degrees of freedom. Older texts use in place of . By the lower bound this gives a larger critical value at the usual levels, so it rejects less often than the Welch rule on the same data.
- Several groups. Welch also gave an analogue of one-way ANOVA for several means with unequal variances.
- Resampling and rank tests. The bootstrap of the Welch statistic is also approximate. The Mann-Whitney U test and the permutation test are exact only for the hypothesis that both samples have the same distribution, which includes equal variances, so they do not solve the Behrens-Fisher problem either.
When to use it
Use Welch's test to compare the means of two independent groups of roughly normal data, or of larger groups of any shape with finite variance, whenever the variances are not known to be equal. Many texts now make it the default two-sample t-test: when the variances are equal it loses little against the pooled test, and when they differ it keeps the size near while the pooled test can have a size of 0.30 or 0.001. For paired data use the paired t-test instead. With a group of 2 or 3 observations, treat its p-value as rough.
Pitfalls
- Treating the test as exact. It is an approximation; with and equal variances the measured size is 0.119 at nominal 0.05.
- Rounding to an integer before looking up a table. This is unnecessary with a tail function that accepts real , and rounding down or up changes the p-value.
- Choosing between pooled and Welch by a preliminary test of equal variances. The two-stage procedure does not have the nominal size, and the variance test has little power at the small sizes where the choice matters.
- Using it on paired data. The groups must be independent; for paired measurements the test ignores the pairing and loses power.
- Reading the degrees of freedom as a sample size. is a property of the variance estimate and changes from sample to sample.
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)
welch_core.py 60 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/welch-t-test/. The authors are listed in prov/C3KW5Q.jsonl.
"""Welch's two-sample t-test with the Welch-Satterthwaite degrees of freedom.
welch_t_test returns (t, nu, p): the statistic, the approximate degrees of
freedom (a real number) and the p-value for the alternative "two-sided",
"greater" (H_1: mu_x - mu_y > delta0) or "less". Both sample variances use the
divisor n - 1 and the two-pass formula. The code is in this file and not in
welch_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 welch_df(a: float, m: int, b: float, n: int) -> float:
"""The Welch-Satterthwaite degrees of freedom for the variance estimate a + b.
a = S_x^2 / m and b = S_y^2 / n are the two estimated variances of the
means, with m - 1 and n - 1 degrees of freedom.
"""
if a < 0.0 or b < 0.0 or a + b == 0.0 or m < 2 or n < 2:
raise ValueError("need a, b >= 0 with a + b > 0, and m, n >= 2")
return (a + b) ** 2 / (a * a / (m - 1) + b * b / (n - 1))
def _mean_var(x: Sequence[float]) -> tuple[float, float]:
"""The mean and S^2 with divisor len(x) - 1, by two passes."""
k = len(x)
mean = math.fsum(x) / k
return mean, math.fsum((v - mean) ** 2 for v in x) / (k - 1)
def welch_t_test(x: Sequence[float], y: Sequence[float], delta0: float = 0.0,
alternative: str = "two-sided") -> tuple[float, float, float]:
"""Test H_0: mu_x - mu_y = delta0 for independent normal samples with unequal variances."""
m, n = len(x), len(y)
if m < 2 or n < 2:
raise ValueError("each sample needs at least 2 observations")
mx, vx = _mean_var(x) # @line L1
my, vy = _mean_var(y) # @line L2
a, b = vx / m, vy / n # @line L3
if a + b == 0.0:
raise ValueError("both samples are constant, so the standard error is 0")
t = (mx - my - delta0) / math.sqrt(a + b) # @line L4
nu = welch_df(a, m, b, n) # @line L5
if alternative == "two-sided":
p = min(1.0, 2.0 * t_sf(abs(t), nu))
elif alternative == "greater":
p = t_sf(t, nu)
elif alternative == "less":
p = t_sf(-t, nu)
else:
raise ValueError(f"alternative must be one of {ALTERNATIVES}")
return t, nu, p # @line L6
test_welch_t_test.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/welch-t-test/. The authors are listed in prov/C3KW5Q.jsonl.
import math
import random
from fractions import Fraction
import pytest
from stdist import t_sf
from welch_t_test import welch_df, welch_t_test
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]
SE4 = 4.0 * math.sqrt(0.05 * 0.95 / 4000) # four standard errors of a size near 0.05, r = 4000
def exact_parts(x: list[int], y: list[int]) -> tuple[Fraction, Fraction]:
"""(t^2, nu) in exact arithmetic, from the definitions with divisors m - 1 and n - 1."""
m, n = len(x), len(y)
mx, my = Fraction(sum(x), m), Fraction(sum(y), n)
a = sum((v - mx) ** 2 for v in x) / Fraction(m - 1) / m
b = sum((v - my) ** 2 for v in y) / Fraction(n - 1) / n
nu = (a + b) ** 2 / (a * a / (m - 1) + b * b / (n - 1))
return (mx - my) ** 2 / (a + b), nu
def test_degrees_of_freedom_against_fractions() -> None:
rng = random.Random(12)
checked = 0
for _ in range(80):
m, n = rng.randint(2, 9), rng.randint(2, 9)
x = [rng.randint(-15, 15) for _ in range(m)]
y = [rng.randint(-15, 15) for _ in range(n)]
if len(set(x)) == 1 and len(set(y)) == 1:
continue
t2, nu = exact_parts(x, y)
t, got_nu, _ = welch_t_test(x, y)
assert abs(got_nu - float(nu)) <= 1e-12 * float(nu)
assert abs(t * t - float(t2)) <= 1e-12 * max(1.0, float(t2))
# Proved bounds: min(m, n) - 1 <= nu <= m + n - 2.
assert min(m, n) - 1 <= nu <= m + n - 2
checked += 1
assert checked > 60
def test_degrees_of_freedom_cases() -> None:
# Equal sizes and equal sample variances give the pooled value 2n - 2.
assert abs(welch_df(2.0, 7, 2.0, 7) - 12.0) < 1e-12
# The upper bound m + n - 2 holds with equality when a / (m - 1) = b / (n - 1).
assert abs(welch_df(4.0, 5, 9.0, 10) - 13.0) < 1e-12
# One variance much larger than the other: nu tends to that sample's n - 1.
assert abs(welch_df(1.0, 5, 1e-12, 30) - 4.0) < 1e-9
assert abs(welch_df(1e-12, 5, 1.0, 30) - 29.0) < 1e-9
def test_sleep_data() -> None:
t, nu, p = welch_t_test(DRUG_1, DRUG_2)
assert abs(t - (-1.8608134674868533)) < 1e-9
assert abs(nu - 17.77647351617849) < 1e-9
assert abs(p - 2.0 * t_sf(abs(t), nu)) < 1e-15
assert abs(p - 0.07939414018735817) < 1e-9
def test_equal_sizes_give_the_pooled_statistic() -> None:
rng = random.Random(4)
for _ in range(20):
n = rng.randint(2, 12)
x = [rng.gauss(1.0, 2.0) for _ in range(n)]
y = [rng.gauss(0.0, 0.5) for _ in range(n)]
mx, my = sum(x) / n, sum(y) / n
sp2 = (sum((v - mx) ** 2 for v in x) + sum((v - my) ** 2 for v in y)) / (2 * n - 2)
pooled = (mx - my) / math.sqrt(sp2 * 2.0 / n)
assert abs(welch_t_test(x, y)[0] - pooled) < 1e-10
def null_size(m: int, sd_x: float, n: int, sd_y: float, r: int, seed: int,
alternative: str = "two-sided") -> float:
rng = random.Random(seed)
hits = 0
for _ in range(r):
x = [rng.gauss(5.0, sd_x) for _ in range(m)]
y = [rng.gauss(5.0, sd_y) for _ in range(n)]
hits += welch_t_test(x, y, alternative=alternative)[2] <= 0.05
return hits / r
def test_size_near_alpha_with_unequal_variances_and_sizes() -> None:
# The case where the pooled test has size 0.30. The Welch size is not exactly 0.05
# (about 0.053 in a run with r = 20000), so allow 0.01 on top of 4 standard errors.
assert abs(null_size(5, 3.0, 25, 1.0, 4000, 5) - 0.05) < SE4 + 0.01
assert abs(null_size(5, 1.0, 25, 3.0, 4000, 6) - 0.05) < SE4 + 0.01
def test_one_sided_size() -> None:
assert abs(null_size(8, 2.0, 16, 1.0, 4000, 9, "greater") - 0.05) < SE4 + 0.01
def test_limit_of_one_dominant_variance_is_exact() -> None:
# sigma_y -> 0: the statistic tends to the one-sample t of x, nu tends to m - 1,
# and the size tends to alpha exactly.
assert abs(null_size(4, 1.0, 20, 1e-6, 4000, 7) - 0.05) < SE4
def test_welch_is_only_approximate() -> None:
# With m = 2 and equal variances the size is far above 0.05 (about 0.119 with r = 20000).
assert null_size(2, 1.0, 20, 1.0, 4000, 8) > 0.05 + SE4
def test_bad_input() -> None:
with pytest.raises(ValueError):
welch_t_test([1.0], [1.0, 2.0])
with pytest.raises(ValueError):
welch_t_test([1.0, 1.0], [2.0, 2.0])
with pytest.raises(ValueError):
welch_t_test([1.0, 2.0], [2.0, 3.0], alternative="both")
with pytest.raises(ValueError):
welch_df(0.0, 3, 0.0, 3)
welch_t_test.py 8 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/welch-t-test/. The authors are listed in prov/C3KW5Q.jsonl.
"""Entry point named after the slug. The code lives in welch_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""
from welch_core import ALTERNATIVES, welch_df, welch_t_test
__all__ = ["ALTERNATIVES", "welch_df", "welch_t_test"]
History
The problem of comparing two normal means with unknown and possibly unequal variances was posed by W.-U. Behrens in 1929, and R. A. Fisher gave a fiducial solution in 1935, so the problem carries both names. Neither gave a test whose size is exactly for all variance ratios. F. E. Satterthwaite approximated the law of a linear combination of independent mean squares by a scaled chi-square with matched mean and variance, in 1941 and in the Biometrics Bulletin in 1946. B. L. Welch, in Biometrika in 1947, studied the statistic with separate variance estimates, gave the same approximate degrees of freedom for the two-sample case and higher-order corrections, and so gave the test its name.
References
- B. L. Welch, The generalization of 'Student's' problem when several different population variances are involved, Biometrika 34(1-2), 1947, pp. 28 to 35, The whole paper (the statistic with separate variance estimates, the approximate degrees of freedom and the higher-order corrections)
- F. E. Satterthwaite, An approximate distribution of estimates of variance components, Biometrics Bulletin 2(6), 1946, pp. 110 to 114, The whole paper (a linear combination of independent mean squares approximated by a scaled chi-square law with matched first two moments)
- George Casella and Roger L. Berger, Statistical Inference, second edition, Duxbury, 2002, Section 5.3 (sampling from the normal distribution, the chi-square and t laws used in the derivation) and Chapter 8 (two-sample tests of means)
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 C3KW5Q Edit this page History Report an error Markdown