Algorithmcore
Tukey's range test
Also called Tukey HSD, honestly significant difference, Tukey-Kramer method.
Compares all pairs of k group means with the studentized range law. Family-wise error rate exactly alpha for balanced normal data, at most alpha with unequal sizes.
- Time
- Θ(n + k²) worst · best
- Space
- Θ(k²) extra
- Where
- k = the number of groups; n = the total number of observations
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- John W. Tukey, D. Newman, Clyde Y. Kramer, Anthony J. Hayter, 1953
Tukey's range test, also called Tukey's honestly significant difference (HSD), compares every pair of group means after a one-way ANOVA. It declares two means different when their difference, divided by its standard error, exceeds a critical value of the studentized range distribution. This is the distribution of the range of independent normal means divided by an independent estimate of their standard deviation. Because the largest of all the pairwise statistics is exactly such a range, the test controls the family-wise error rate over all pairs. With equal group sizes and normal errors with a common variance, the simultaneous confidence intervals cover all pairwise differences with probability exactly . With unequal sizes the same formula is the Tukey-Kramer method, which is conservative.
In plain words
After you find that several group averages are not all the same, you want to know which pairs differ. If you test every pair on its own at the 5% level, the chance of at least one false alarm grows with the number of pairs. Tukey asked a different question: how large can the biggest gap between any two averages be when nothing is going on? He took the widest gap, the largest average minus the smallest one, and measured it in units of the noise. Its chance distribution does not depend on the true averages or on the noise level. A pair is declared different only if its gap is larger than what the widest gap would reach by chance in 95% of experiments. So the chance of any false alarm over all pairs together stays at 5%.
The problem
Model. Data for groups () and units , with . The model is with iid errors, as in one-way ANOVA. The error mean square has degrees of freedom. The same procedure applies to the means of any balanced design whose is independent of the means, for example the treatment means of a randomized block design or the marginal means of a balanced two-way ANOVA, with that design's .
Hypotheses. A family of hypotheses for , each against the two-sided alternative. The goal is the family-wise error rate in the strong sense: for every configuration of the means, the probability of rejecting at least one true is at most .
Statistic. For each pair,
With equal sizes the denominator is , the estimated standard error of one mean. The pairwise statistic is times the absolute pooled Student t statistic of the pair, but its standard error uses all groups.
Null distribution. Exact for equal sizes. Let be iid and independent of them. The studentized range is . Its upper tail is the double integral
with the normal upper tail and the density of . Under the model, has exactly the law of , for every and . With unequal sizes no single law is exact, and gives a conservative bound.
Rejection rule and size. Reject when , the upper point of . In the units of the means, the honestly significant difference is , and a pair is declared different when . The simultaneous intervals are . For equal sizes the family-wise error rate is exactly under the complete null and at most under every other configuration. For example and .
p-value. The adjusted p-value of a pair is . Rejecting the pairs with is the same as the rule above. Each is already adjusted for the whole family, so it is compared with directly.
Sensitivity and power. The test is built for pairwise differences. For pairs, its intervals are shorter than those of Scheffé's method and of the Bonferroni correction, and the gap grows with (table under Example). Its power for one pair is lower than that of an unadjusted t-test, which is the price of the family-wise guarantee. For contrasts that involve more than two means, such as one mean against the average of the others, Scheffé's method is often shorter.
The algorithm
TUKEY-HSD(groups y[1..k], α) ▷ k ≥ 2, N > k- 1
(ȳ[1..k], MSE, ν) ← group means, two-pass pooled variance, ν = N - k - 2
q* ← upper α point of Q(k, ν) ▷ invert the tail by false position - 3
for each pair i < j: - 4
d ← ȳ[i] - ȳ[j]; se ← sqrt((MSE / 2)·(1/n[i] + 1/n[j])) - 5
q ← |d| / se - 6
p ← P(Q(k, ν) > q) ▷ the double integral by Gauss-Legendre panels - 7
record (i, j, d, q, p, d - q*·se, d + q*·se) - 8
return (q*, the records)
The tail in L6 is the double integral above. The inner integral over uses 17 panels of a 10-point Gauss-Legendre quadrature rule on , and the outer integral over uses 40 panels on the range that holds all but of the chi-square mass. For the outer integral is dropped. L2 finds a bracket by doubling and then runs the Illinois variant of regula falsi on . The code rejects , empty groups, and .
Example
The three groups below have equal sizes , so , and :
| group | data | ||
|---|---|---|---|
| A | 5, 7, 6, 8, 4 | 6 | 10 |
| B | 9, 11, 10, 12, 8 | 10 | 10 |
| C | 6, 8, 7, 5, 9 | 7 | 10 |
L1 gives , and the ANOVA F statistic is on degrees of freedom. L2 gives . The standard error of one mean is , so .
| pair | (L5) | adjusted (L6) | 95% simultaneous interval (L7) | |
|---|---|---|---|---|
| A - B | 5.657 | 0.004634 | ||
| A - C | 1.414 | 0.5908 | ||
| B - C | 4.243 | 0.02772 |
B differs from A and from C at the 5% family-wise level, and the data do not separate A from C.
Width of the intervals. The half-widths of 95% intervals for one pairwise difference, in units of its standard error , are for Tukey, for Scheffé, for Bonferroni over the pairs, and for the unadjusted t-test:
| , | Tukey | Scheffé | Bonferroni | unadjusted |
|---|---|---|---|---|
| 3, 12 (the example) | 2.6679 | 2.7876 | 2.7795 | 2.1788 |
| 3, 30 | 2.4653 | 2.5752 | 2.5357 | 2.0423 |
| 5, 30 | 2.9006 | 3.2800 | 3.0298 | 2.0423 |
| 10, 30 | 3.4112 | 4.4605 | 3.6067 | 2.0423 |
Family-wise error rate by simulation. Normal data with all means equal, , 20000 replications (standard error near 0.0015):
| group sizes | measured rate of at least one false rejection | seed |
|---|---|---|
| 5, 5, 5, 5 | 0.05255 | 1 |
| 3, 5, 10, 20 | 0.0485 | 2 |
| 2, 2, 30, 30 | 0.0436 | 3 |
The balanced rate is within two standard errors of the exact 0.05. With unequal sizes the Tukey-Kramer rate falls below 0.05, as Hayter's theorem says.
Accuracy of the studentized range. The tail of L6 against the share of 20000 simulated values of above (seed 4, standard error at most 0.0036):
| simulated | L6 | |
|---|---|---|
| 2 | 0.5207 | 0.51896 |
| 3 | 0.2115 | 0.21111 |
| 4 | 0.07085 | 0.07208 |
| 5 | 0.0244 | 0.02345 |
L2 reproduces published table values, for example , , , , , and .
Correctness
Let all sizes be and put . The are iid standard normal, and is and independent of the means, because the group means and the within-group residuals are projections of the data onto orthogonal subspaces (the one-way ANOVA proof). Each centred pairwise statistic is , and the largest of them over all pairs is . So all intervals cover at once exactly when , which has probability . A false rejection of a true means that the interval for misses, so the family-wise error rate is at most for every configuration, and equal to when all means are equal. The double integral comes from conditioning on the smallest and then on . For two groups , so the test is the two-sided pooled t-test, which gives an exact check of the quadrature. The full proofs are in the correctness proof below. The coverage of Tukey-Kramer with unequal sizes is Hayter's theorem, cited and not proved here, and the accuracy of the quadrature is measured, not bounded.
Proof: Tukey's test has family-wise error rate exactly alpha for balanced normal datafull
We prove that for balanced normal data the largest standardized pairwise difference of the group means, centred at the true means, has the studentized range law, so the Tukey intervals cover all pairwise differences at once with probability exactly and the tests control the family-wise error rate at in the strong sense. We derive the integral that the helper evaluates, and the exact check for two groups. The model is , , , with iid errors, , , and .
Definition. Let be iid and independent of them. The range is , and the studentized range is . For , . is its upper point.
Lemma 1 (the law of the range). For ,
and, with ,
Proof. With probability 1 the are distinct, so exactly one index attains the minimum. happens exactly when, for the index of the minimum, every other lies in . These events are disjoint. Conditioning on , the other variables are independent with , which gives the first formula after integrating against and adding the equal terms. The same argument with gives (some index is the minimum). Subtract the first formula from this and use .
The helper evaluates the bracket as with , which is the same number written without the cancellation of two nearly equal powers in the tails.
Lemma 2 (the law of ). , where is the density of : .
Proof. and are independent, so . The density of follows from the density of by the change of variables , .
Lemma 3 (the pivot). Let all . Then
Proof. Let . The are iid , because the groups are independent and each is the mean of iid errors. is independent of the vector of group means by Lemma 3 of the one-way ANOVA proof (the within-group residuals and the group means are projections onto orthogonal subspaces). Then . The largest over pairs is .
Lemma 4 (exact simultaneous coverage). With equal sizes the code's interval for is , and
for every and .
Proof. The code's standard error is , which is when . All intervals cover if and only if the maximum in Lemma 3 is at most . The law of is continuous, so this has probability exactly .
Lemma 5 (strong FWER control). With equal sizes, reject when , which is the same as . For every configuration of the means, the probability of rejecting at least one true is at most , and it equals when all means are equal.
Proof. If is true and rejected, then , so the interval for misses. By Lemma 4 the probability that some interval misses is . When all means are equal, every is true, and some is rejected exactly when the maximum in Lemma 3 exceeds , which has probability . The p-value form is the same event because is strictly decreasing.
This is the family-wise error rate in the strong sense, under the normal model with equal variances and equal group sizes, with no other assumption on the dependence of the tests.
Lemma 6 (two groups). For , with , and the code's statistic is , where is the pooled two-sample t statistic. So .
Proof. and , so with , and . For the statistic: the pooled t uses and the standard error , while the code divides by , which is smaller by the factor . This holds for unequal sizes as well.
This gives an exact check of the numerical integration, which the tests run for several .
What is measured, not proved. The helper computes Lemma 2 by composite Gauss-Legendre rules: 17 panels of 10 nodes on for the inner integral and 40 panels of 10 nodes for the outer one, over the range of that holds all but of the chi-square mass. Its error is measured, not bounded: it matches Lemma 6 to for and to for up to 1000, it reproduces published table values of to the printed digits, and it agrees with Monte Carlo within the sampling error. With unequal sizes, the Tukey-Kramer intervals have coverage at least ; this is Hayter's theorem (1984), which we cite and do not prove.
Termination. L1 makes two passes over the data. L2 inverts the tail by Illinois false position with at most 100 steps after a doubling search for an upper bracket, which stops because as grows. Each tail evaluation is a fixed number of quadrature nodes, outer times inner. The pair loop runs times with one tail evaluation each.
Theorem. Under the normal model with equal variances and equal group sizes, the intervals returned by the code have simultaneous coverage exactly , the pairwise tests control the family-wise error rate at exactly under the complete null and at most under every other configuration, and with two groups the test is the two-sided pooled t-test. The accuracy of the numerical studentized range is measured as stated above.
Proof. Lemmas 1 to 6.
Complexity
On a real RAM, L1 makes two passes over the observations, . The loop L3 to L7 runs times. Each tail evaluation in L6 is a fixed number of quadrature nodes, outer times inner, independent of and , so the loop costs with a large constant. L2 costs a doubling search and at most 100 false position steps of one tail each. The total time is , and the extra space is for the records. In the Python code, one tail takes about 0.02 s and the quantile about 0.3 s.
Numerical stability. subtracts each group mean before squaring, as in the one-way code, which avoids catastrophic cancellation for large values with a small spread. In the inner integrand, is the difference of two nearly equal powers when is large. The code writes it as with , which keeps its relative accuracy. It computes the upper tail directly: for and , a tail of agrees with the exact t tail to a relative error of . The check against agrees to for and to for up to 1000.
Properties
- Exact for balanced data. Simultaneous coverage and family-wise error rate under the complete null, for every , and .
- Strong control. The error rate is at most under every configuration of the means, not only under the complete null.
- Two groups. and , so the test is the two-sided pooled t-test.
- Single step. Every pair uses the same critical value, so the intervals are simultaneous and consistent: the intervals and the tests give the same decisions.
- Shortest for all pairs. Among single-step methods for all pairwise differences with equal sizes, the Tukey intervals are shorter than the Scheffé and Bonferroni intervals for (table above).
- No preliminary F-test needed. Its guarantee does not depend on the ANOVA F-test. A pair can be significant while F is not, and the reverse.
- Not transitive. With three ordered means, the test can separate the two outer means but neither of them from the middle one. So the results are often shown as overlapping groups of means, not as a partition.
Variants and improvements
- Tukey-Kramer method. With unequal sizes, use the standard error of each pair and the same (Kramer, 1956). The code above is already this method. Hayter (1984) proved that its coverage is at least , and the simulation above shows rates of 0.0485 and 0.0436. On the one-way ANOVA example with sizes 4, 5 and 6 (), it gives the adjusted p-values 0.00920 for A - B, 0.855 for A - C and 0.01275 for B - C.
- All contrasts. Tukey's intervals extend to every contrast with : , with simultaneous coverage at least . For pairwise differences this is the HSD itself; for contrasts with many nonzero terms, Scheffé's method is shorter.
- Unequal variances. The Games-Howell method uses the Welch standard error and Welch degrees of freedom for each pair. Its error rate is approximate, not guaranteed. See the Welch t-test.
- Comparisons with a control. When only comparisons with one control group are of interest, Dunnett's method uses the maximum of correlated t statistics and gives shorter intervals than Tukey's.
- Stepwise range tests. The Newman-Keuls procedure uses for a range of ordered means. It does not control the family-wise error rate in the strong sense for . The Ryan-Einot-Gabriel-Welsch procedure adjusts the levels so that it does, and it is a shortcut of the closed testing principle. Stepwise methods are more powerful than Tukey's test but do not give simultaneous intervals.
- Other designs. In a randomized block design or a balanced two-way ANOVA, use the means of one factor, the of that design and its error degrees of freedom.
When to use it
Use Tukey's test when all pairwise comparisons of means are of interest, the sizes are equal or close to equal, and the errors are close to normal with a common variance. Use Tukey-Kramer for unequal sizes. Use Dunnett's method when only comparisons with a control matter, the Bonferroni correction or the Holm-Bonferroni method for a few planned comparisons, and Scheffé's method when contrasts other than pairs are chosen after looking at the data. Use Games-Howell when the variances clearly differ.
Pitfalls
- Unequal variances with unequal sizes. The pooled is wrong for each pair, and the error rate can be far from , as for the one-way ANOVA F-test.
- Gating on the F-test. Running Tukey's test only after a significant F changes its error rate and its power. The test does not need the gate.
- Reading adjusted p-values as unadjusted. already accounts for all pairs; do not apply another correction to it.
- The factor. Some tables and programs divide by and others by . Compare with , or with , never a mixture.
- Wrong or . is the number of means in the family, not the number of pairs, and is the error degrees of freedom of the whole analysis, not .
- Data dredging beyond pairs. Choosing a non-pairwise contrast after looking at the data needs Scheffé's method; see the multiple comparisons problem.
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 ci3 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The studentized range distribution in the standard library.
Q = R / S, where R is the range of k iid N(0, 1) variables and nu S^2 is an
independent chi-square with nu degrees of freedom (nu = inf means S = 1).
P(R > w) = k * integral phi(z) (A(z)^(k-1) - (A(z) - A(z + w))^(k-1)) dz,
A(z) = P(Z > z),
because the minimum of the k variables has density k phi(z) A(z)^(k-1), and
given the minimum z the other k - 1 lie in (z, z + w] with probability
((A(z) - A(z + w)) / A(z))^(k-1). The difference of powers is written as
-A^(k-1) expm1((k-1) log1p(-A(z + w) / A(z))), so a small tail keeps its
digits. Then P(Q > q) = integral g(s) P(R > q s) ds, where g is the density of
S. Both integrals use composite Gauss-Legendre rules; the outer range of s
holds all but 1e-30 of the mass of S. The tail is accurate to about 1e-11
absolutely for 2 <= k <= 100 and nu >= 1 (the tests compare it with the exact
k = 2 law and with Monte Carlo).
"""
import math
from stdist import chi2_cdf, chi2_sf, norm_sf
_SQRT_2PI = math.sqrt(2.0 * math.pi)
def _legendre_rule(m: int) -> list[tuple[float, float]]:
"""Nodes and weights of the m-point Gauss-Legendre rule on [-1, 1], by Newton's method."""
rule = []
for i in range(1, m + 1):
x = math.cos(math.pi * (i - 0.25) / (m + 0.5))
for _ in range(100):
p0, p1 = 1.0, x
for j in range(2, m + 1):
p0, p1 = p1, ((2 * j - 1) * x * p1 - (j - 1) * p0) / j
dp = m * (x * p1 - p0) / (x * x - 1.0)
dx = p1 / dp
x -= dx
if abs(dx) < 1e-16:
break
p0, p1 = 1.0, x
for j in range(2, m + 1):
p0, p1 = p1, ((2 * j - 1) * x * p1 - (j - 1) * p0) / j
dp = m * (x * p1 - p0) / (x * x - 1.0)
rule.append((x, 2.0 / ((1.0 - x * x) * dp * dp)))
return rule
_RULE = _legendre_rule(10)
def _panels(lo: float, hi: float, count: int) -> list[tuple[float, float]]:
"""Nodes and weights of the composite rule with count equal panels on [lo, hi]."""
h = (hi - lo) / count
out = []
for p in range(count):
mid = lo + (p + 0.5) * h
out += [(mid + 0.5 * h * x, 0.5 * h * w) for x, w in _RULE]
return out
Z_PANELS = 17 # panels of the inner rule on [-8.5, 8.5]
S_PANELS = 40 # panels of the outer rule
# Inner nodes z with the weight times phi(z), and A(z), computed once.
_Z_NODES = [(z, wt * math.exp(-0.5 * z * z) / _SQRT_2PI, norm_sf(z))
for z, wt in _panels(-8.5, 8.5, Z_PANELS)]
def range_sf(w: float, k: int) -> float:
"""P(R > w) for the range R of k iid standard normal variables."""
if k < 2:
raise ValueError("need k >= 2")
if w <= 0.0:
return 1.0
m = k - 1
total = 0.0
for z, wphi, a in _Z_NODES:
r = norm_sf(z + w) / a
diff = a ** m if r >= 1.0 else -(a ** m) * math.expm1(m * math.log1p(-r))
total += wphi * diff
return min(1.0, k * total)
def _chi2_point(nu: float, mass: float, upper: bool) -> float:
"""The x with P(X <= x) = mass (upper = False) or P(X > x) = mass, X chi-square with nu df."""
f = (lambda x: chi2_sf(x, nu)) if upper else (lambda x: chi2_cdf(x, nu))
lo, hi = 0.0, max(1.0, nu)
if upper:
while f(hi) > mass:
lo, hi = hi, 2.0 * hi
else:
while f(lo) < mass and lo == 0.0 and f(hi) < mass:
hi *= 2.0
for _ in range(200):
mid = 0.5 * (lo + hi)
if mid <= lo or mid >= hi:
break
if (f(mid) > mass) == upper:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
def srange_sf(q: float, k: int, nu: float) -> float:
"""P(Q > q) for the studentized range with k means and nu degrees of freedom."""
if q <= 0.0:
return 1.0
if math.isinf(nu):
return range_sf(q, k)
s_lo = math.sqrt(_chi2_point(nu, 1e-30, False) / nu)
s_hi = math.sqrt(_chi2_point(nu, 1e-30, True) / nu)
# log of the density of S: nu^(nu/2) s^(nu-1) exp(-nu s^2 / 2) / (Gamma(nu/2) 2^(nu/2 - 1))
log_c = 0.5 * nu * math.log(nu) - math.lgamma(0.5 * nu) - (0.5 * nu - 1.0) * math.log(2.0)
total = 0.0
for s, wt in _panels(s_lo, s_hi, S_PANELS):
if s <= 0.0:
continue
dens = math.exp(log_c + (nu - 1.0) * math.log(s) - 0.5 * nu * s * s)
total += wt * dens * range_sf(q * s, k)
return min(1.0, total)
def srange_cdf(q: float, k: int, nu: float) -> float:
"""P(Q <= q)."""
return 1.0 - srange_sf(q, k, nu)
def srange_ppf(p: float, k: int, nu: float) -> float:
"""The lower p-quantile of the studentized range, by bisection on the upper tail."""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
tail = 1.0 - p
lo, hi = 0.0, 4.0
while srange_sf(hi, k, nu) > tail:
lo, hi = hi, 2.0 * hi
# Illinois false position on log tail, then a few bisection steps if it stalls.
g = lambda x: math.log(srange_sf(x, k, nu)) - math.log(tail)
a, b = lo, hi
ga, gb = (math.inf if a == 0.0 else g(a)), g(b)
if math.isinf(ga):
a = 0.5 * b
ga = g(a)
while ga < 0.0:
b, gb = a, ga
a = 0.5 * a
ga = g(a)
side = 0
for _ in range(100):
x = b - gb * (b - a) / (gb - ga)
gx = g(x)
if abs(gx) < 1e-13 or abs(b - a) < 1e-12 * b:
return x
if gx * gb > 0.0:
b, gb = x, gx
if side == -1:
ga *= 0.5
side = -1
else:
a, ga = x, gx
if side == 1:
gb *= 0.5
side = 1
return 0.5 * (a + b)
stdist.py 238 lines
# 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)
tukey_hsd.py 58 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tukey-hsd/. The authors are listed in prov/N35W2Z.jsonl.
"""Tukey's honestly significant difference test for all pairwise differences of k means.
For each pair (i, j) the statistic is q = |ybar_i - ybar_j| / sqrt((MSE / 2)(1/n_i + 1/n_j)),
with MSE the pooled within-group variance on nu = N - k degrees of freedom. The adjusted
p-value is P(Q > q) for the studentized range Q with k means and nu degrees of freedom, and
the simultaneous interval is ybar_i - ybar_j +- q_crit sqrt((MSE / 2)(1/n_i + 1/n_j)).
With equal group sizes this is Tukey's test, whose family-wise coverage is exactly 1 - alpha
under the normal model. With unequal sizes the same formula is the Tukey-Kramer method,
whose coverage is at least 1 - alpha (Hayter, 1984).
"""
import math
from collections.abc import Sequence
from typing import NamedTuple
from srange import srange_ppf, srange_sf
class Pair(NamedTuple):
i: int
j: int
diff: float # ybar_i - ybar_j
se: float # sqrt((MSE / 2)(1/n_i + 1/n_j))
q: float # |diff| / se
p: float # P(Q_(k, nu) > q), the adjusted p-value
lo: float # simultaneous interval for mu_i - mu_j
hi: float
def means_and_mse(groups: Sequence[Sequence[float]]) -> tuple[list[float], float, int]:
"""Group means, the pooled within-group mean square (two-pass) and its degrees of freedom."""
k = len(groups)
big_n = sum(len(g) for g in groups)
if k < 2 or any(len(g) == 0 for g in groups) or big_n <= k:
raise ValueError("need k >= 2 nonempty groups and N > k")
means = [math.fsum(g) / len(g) for g in groups]
ssw = math.fsum((v - m) ** 2 for g, m in zip(groups, means) for v in g)
if ssw == 0.0:
raise ValueError("every group is constant, so MSE = 0")
return means, ssw / (big_n - k), big_n - k
def tukey_hsd(groups: Sequence[Sequence[float]], alpha: float = 0.05) -> tuple[float, list[Pair]]:
"""(q_crit, pairs): the critical value of the studentized range and one record per pair i < j."""
k = len(groups)
means, mse, nu = means_and_mse(groups) # @line L1
q_crit = srange_ppf(1.0 - alpha, k, nu) # @line L2
pairs = []
for i in range(k): # @line L3
for j in range(i + 1, k):
diff = means[i] - means[j] # @line L4
se = math.sqrt(0.5 * mse * (1.0 / len(groups[i]) + 1.0 / len(groups[j])))
q = abs(diff) / se # @line L5
p = srange_sf(q, k, nu) # @line L6
pairs.append(Pair(i, j, diff, se, q, p, diff - q_crit * se, diff + q_crit * se)) # @line L7
return q_crit, pairs # @line L8
test_tukey_hsd.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tukey-hsd/. The authors are listed in prov/N35W2Z.jsonl.
import math
import random
from fractions import Fraction
import pytest
from srange import range_sf, srange_ppf, srange_sf
from stdist import norm_sf, t_sf
from tukey_hsd import means_and_mse, tukey_hsd
EXAMPLE = [[5, 7, 6, 8, 4], [9, 11, 10, 12, 8], [6, 8, 7, 5, 9]]
def test_two_means_is_the_t_law() -> None:
# With k = 2 the range is |Z1 - Z2| = sqrt(2) |N(0, 1)|, so P(Q > q) = 2 P(T > q / sqrt(2)).
for nu in (1, 2, 5, 12, 40, 1000):
for q in (0.2, 1.0, 2.0, 3.5, 6.0, 10.0):
assert abs(srange_sf(q, 2, nu) - 2.0 * t_sf(q / math.sqrt(2.0), nu)) < 1e-12
for w in (0.1, 1.0, 3.0, 6.0):
assert abs(range_sf(w, 2) - 2.0 * norm_sf(w / math.sqrt(2.0))) < 1e-15
def test_range_of_three_closed_form() -> None:
# Known values of P(R <= w) for the range of 3 standard normals (k = 3, nu = inf):
# the 0.95 quantile is 3.314 and the 0.99 quantile is 4.120 to the 3 decimals of the tables.
assert abs(srange_ppf(0.95, 3, math.inf) - 3.314) < 5e-4
assert abs(srange_ppf(0.99, 3, math.inf) - 4.120) < 5e-4
def test_table_values() -> None:
# Upper 5% points of the studentized range, as printed to 3 decimals.
for k, nu, q in ((3, 10, 3.877), (5, 5, 5.673), (10, 20, 5.008)):
assert abs(srange_ppf(0.95, k, nu) - q) < 5e-4
def test_against_monte_carlo() -> None:
rng = random.Random(4)
reps, k, nu = 20000, 4, 10
draws = []
for _ in range(reps):
z = [rng.gauss(0.0, 1.0) for _ in range(k)]
s = math.sqrt(sum(rng.gauss(0.0, 1.0) ** 2 for _ in range(nu)) / nu)
draws.append((max(z) - min(z)) / s)
for q in (2.0, 3.0, 4.0, 5.0):
p = srange_sf(q, k, nu)
observed = sum(d > q for d in draws) / reps
assert abs(observed - p) < 4.5 * math.sqrt(p * (1 - p) / reps)
def test_example() -> None:
q_crit, pairs = tukey_hsd(EXAMPLE)
assert abs(q_crit - 3.7729289657270066) < 1e-8
got = {(p.i, p.j): p for p in pairs}
assert [round(got[key].diff, 12) for key in ((0, 1), (0, 2), (1, 2))] == [-4.0, -1.0, 3.0]
assert abs(got[0, 1].q - 4.0 * math.sqrt(2.0)) < 1e-12
assert abs(got[0, 1].p - 0.004634080571702173) < 1e-9
assert abs(got[1, 2].p - 0.02772191558007049) < 1e-9
assert abs(got[0, 2].p - 0.590770608320337) < 1e-9
assert got[0, 1].hi < 0.0 and got[1, 2].lo > 0.0 and got[0, 2].lo < 0.0 < got[0, 2].hi
def test_statistic_against_fractions() -> None:
rng = random.Random(7)
for _ in range(40):
groups = [[rng.randint(0, 40) for _ in range(rng.randint(1, 6))] for _ in range(rng.randint(2, 5))]
k, big_n = len(groups), sum(len(g) for g in groups)
means = [Fraction(sum(g), len(g)) for g in groups]
ssw = sum((v - m) ** 2 for g, m in zip(groups, means) for v in g)
if big_n <= k or ssw == 0:
continue
mse = ssw / (big_n - k)
_, mse_f, nu = means_and_mse(groups)
assert nu == big_n - k and abs(mse_f - float(mse)) <= 1e-12 * float(mse)
for i in range(k):
for j in range(i + 1, k):
q2 = (means[i] - means[j]) ** 2 / (mse / 2 * (Fraction(1, len(groups[i])) + Fraction(1, len(groups[j]))))
se = math.sqrt(0.5 * mse_f * (1.0 / len(groups[i]) + 1.0 / len(groups[j])))
q = abs(float(means[i] - means[j])) / se
assert abs(q * q - float(q2)) <= 1e-10 * max(1.0, float(q2))
def test_two_groups_match_the_pooled_t_test() -> None:
rng = random.Random(8)
for _ in range(3):
x = [rng.gauss(0.0, 1.0) for _ in range(rng.randint(2, 8))]
y = [rng.gauss(0.7, 1.0) for _ in range(rng.randint(2, 8))]
_, [pair] = tukey_hsd([x, y])
mx, my = sum(x) / len(x), sum(y) / len(y)
sp2 = (sum((v - mx) ** 2 for v in x) + sum((v - my) ** 2 for v in y)) / (len(x) + len(y) - 2)
t = (mx - my) / math.sqrt(sp2 * (1 / len(x) + 1 / len(y)))
assert abs(pair.q - math.sqrt(2.0) * abs(t)) < 1e-12
assert abs(pair.p - 2.0 * t_sf(abs(t), len(x) + len(y) - 2)) < 1e-12
def family_wise_error(seed: int, sizes: list[int], reps: int) -> float:
rng = random.Random(seed)
k, nu = len(sizes), sum(sizes) - len(sizes)
q_crit = srange_ppf(0.95, k, nu)
hits = 0
for _ in range(reps):
groups = [[rng.gauss(0.0, 1.0) for _ in range(n)] for n in sizes]
means, mse, _ = means_and_mse(groups)
worst = max(abs(means[i] - means[j]) / math.sqrt(0.5 * mse * (1 / sizes[i] + 1 / sizes[j]))
for i in range(k) for j in range(i + 1, k))
hits += worst > q_crit
return hits / reps
def test_family_wise_error_is_alpha_when_balanced() -> None:
reps = 6000
rate = family_wise_error(1, [5, 5, 5, 5], reps)
assert abs(rate - 0.05) < 4.0 * math.sqrt(0.05 * 0.95 / reps)
def test_tukey_kramer_is_conservative() -> None:
reps = 6000
rate = family_wise_error(3, [2, 2, 30, 30], reps)
assert rate < 0.05 + 3.0 * math.sqrt(0.05 * 0.95 / reps)
def test_errors() -> None:
with pytest.raises(ValueError):
tukey_hsd([[1.0, 2.0]])
with pytest.raises(ValueError):
tukey_hsd([[1.0, 1.0], [2.0, 2.0]])
with pytest.raises(ValueError):
srange_ppf(1.0, 3, 10)
History
"Student" studied the distribution of the range of normal samples in 1927, and D. Newman tabulated the range divided by an independent estimate of the standard deviation in 1939. John W. Tukey proposed the honestly significant difference in a long manuscript, The Problem of Multiple Comparisons, which he circulated in 1953 and which was printed only in 1994 in his Collected Works. Clyde Y. Kramer extended the method to unequal group sizes in 1956, and the conjecture that the extension is conservative stayed open until Anthony J. Hayter proved it in 1984. Lund and Lund published a widely used algorithm for the distribution in 1983.
References
- John W. Tukey, The Collected Works of John W. Tukey, Volume VIII: Multiple Comparisons 1948-1983, edited by Henry I. Braun, Chapman and Hall, 1994, the 1953 manuscript The Problem of Multiple Comparisons, first printed in this volume (chapter-level locator)
- Clyde Young Kramer, Extension of multiple range tests to group means with unequal numbers of replications, Biometrics 12(3), 1956, pp. 307 to 310 (the standard error with the harmonic term for unequal sizes)
- A. J. Hayter, A proof of the conjecture that the Tukey-Kramer multiple comparisons procedure is conservative, Annals of Statistics 12(1), 1984, pp. 61 to 75 (the coverage of the Tukey-Kramer intervals is at least 1 - alpha)
- R. E. Lund and J. R. Lund, Algorithm AS 190: probabilities and upper quantiles for the studentized range, Applied Statistics 32(2), 1983, pp. 204 to 210 (the double integral and its numerical evaluation; a correction appeared in Applied Statistics 34(1), 1985, p. 104)
- Yoav Benjamini and Henry Braun, John W. Tukey's contributions to multiple comparisons, Annals of Statistics 30(6), 2002, pp. 1576 to 1594 (the history of the 1953 manuscript and of the honestly significant difference)
- Douglas C. Montgomery, Design and Analysis of Experiments, tenth edition, Wiley, 2019, Chapter 3 (comparing pairs of treatment means after the analysis of variance; chapter-level locator)
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 N35W2Z Edit this page History Report an error Markdown