Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
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 kk 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 kk 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 k(k−1)/2k(k-1)/2 pairs. With equal group sizes and normal errors with a common variance, the simultaneous confidence intervals cover all pairwise differences with probability exactly 1−α1 - \alpha. 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 yijy_{ij} for groups i=1,…,ki = 1, \dots, k (k≥2k \ge 2) and units j=1,…,nij = 1, \dots, n_i, with N=∑ini>kN = \sum_i n_i > k. The model is yij=μi+eijy_{ij} = \mu_i + e_{ij} with iid N(0,σ2)N(0, \sigma^2) errors, as in one-way ANOVA. The error mean square MSE=1ν∑i,j(yij−yˉi)2MSE = \frac1\nu\sum_{i,j}(y_{ij} - \bar y_i)^2 has ν=N−k\nu = N - k degrees of freedom. The same procedure applies to the means of any balanced design whose MSEMSE 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 ν\nu.

Hypotheses. A family of m=k(k−1)/2m = k(k-1)/2 hypotheses Hij:μi=μjH_{ij}: \mu_i = \mu_j for i<ji < j, 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 HijH_{ij} is at most α\alpha.

Statistic. For each pair,

qij=∣yˉi−yˉj∣MSE2(1ni+1nj).q_{ij} = \frac{|\bar y_i - \bar y_j|}{\sqrt{\frac{MSE}{2}\left(\frac1{n_i} + \frac1{n_j}\right)}} .

With equal sizes ni=nn_i = n the denominator is MSE/n\sqrt{MSE/n}, the estimated standard error of one mean. The pairwise statistic is 2\sqrt2 times the absolute pooled Student t statistic of the pair, but its standard error uses all kk groups.

Null distribution. Exact for equal sizes. Let Z1,…,ZkZ_1, \dots, Z_k be iid N(0,1)N(0, 1) and V∼χν2V \sim \chi^2_\nu independent of them. The studentized range is Qk,ν=(max⁡iZi−min⁡iZi)/V/νQ_{k,\nu} = (\max_i Z_i - \min_i Z_i)/\sqrt{V/\nu}. Its upper tail is the double integral

P(Qk,ν>q)=∫0∞gν(s) k∫−∞∞φ(z)(A(z)k−1−(A(z)−A(z+qs))k−1)dz ds,P(Q_{k,\nu} > q) = \int_0^\infty g_\nu(s)\,k\int_{-\infty}^{\infty}\varphi(z)\Big(A(z)^{k-1} - \big(A(z) - A(z + qs)\big)^{k-1}\Big)dz\,ds,

with A=1−ΦA = 1 - \Phi the normal upper tail and gνg_\nu the density of V/ν\sqrt{V/\nu}. Under the model, max⁡i<j∣(yˉi−yˉj)−(μi−μj)∣/MSE/n\max_{i<j}|(\bar y_i - \bar y_j) - (\mu_i - \mu_j)|/\sqrt{MSE/n} has exactly the law of Qk,νQ_{k,\nu}, for every μ\mu and σ\sigma. With unequal sizes no single law is exact, and Qk,νQ_{k,\nu} gives a conservative bound.

Rejection rule and size. Reject HijH_{ij} when qij>q(k,ν,1−α)q_{ij} > q_{(k,\nu,1-\alpha)}, the upper α\alpha point of Qk,νQ_{k,\nu}. In the units of the means, the honestly significant difference is HSD=q(k,ν,1−α)MSE/nHSD = q_{(k,\nu,1-\alpha)}\sqrt{MSE/n}, and a pair is declared different when ∣yˉi−yˉj∣>HSD|\bar y_i - \bar y_j| > HSD. The simultaneous intervals are yˉi−yˉj±q(k,ν,1−α)MSE2(1ni+1nj)\bar y_i - \bar y_j \pm q_{(k,\nu,1-\alpha)}\sqrt{\frac{MSE}2(\frac1{n_i} + \frac1{n_j})}. For equal sizes the family-wise error rate is exactly α\alpha under the complete null and at most α\alpha under every other configuration. For example q(3,12,0.95)=3.77293q_{(3,12,0.95)} = 3.77293 and q(3,∞,0.95)=3.314q_{(3,\infty,0.95)} = 3.314.

p-value. The adjusted p-value of a pair is pij=P(Qk,ν>qij)p_{ij} = P(Q_{k,\nu} > q_{ij}). Rejecting the pairs with pij≤αp_{ij} \le \alpha is the same as the rule above. Each pijp_{ij} is already adjusted for the whole family, so it is compared with α\alpha 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 kk (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

  1. TUKEY-HSD(groups y[1..k], α) ▷ k ≥ 2, N > k
  2. 1(ȳ[1..k], MSE, ν) ← group means, two-pass pooled variance, ν = N - k
  3. 2q* ← upper α point of Q(k, ν) ▷ invert the tail by false position
  4. 3for each pair i < j:
  5. 4d ← ȳ[i] - ȳ[j]; se ← sqrt((MSE / 2)·(1/n[i] + 1/n[j]))
  6. 5q ← |d| / se
  7. 6p ← P(Q(k, ν) > q) ▷ the double integral by Gauss-Legendre panels
  8. 7record (i, j, d, q, p, d - q*·se, d + q*·se)
  9. 8return (q*, the records)

The tail in L6 is the double integral above. The inner integral over zz uses 17 panels of a 10-point Gauss-Legendre quadrature rule on [−8.5,8.5][-8.5, 8.5], and the outer integral over ss uses 40 panels on the range that holds all but 10−3010^{-30} of the chi-square mass. For ν=∞\nu = \infty the outer integral is dropped. L2 finds a bracket by doubling and then runs the Illinois variant of regula falsi on P(Q>q)−αP(Q > q) - \alpha. The code rejects N≤kN \le k, empty groups, and MSE=0MSE = 0.

Example

The three groups below have equal sizes n=5n = 5, so k=3k = 3, N=15N = 15 and ν=12\nu = 12:

group data yˉi\bar y_i ∑j(yij−yˉi)2\sum_j (y_{ij} - \bar y_i)^2
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 MSE=30/12=2.5MSE = 30/12 = 2.5, and the ANOVA F statistic is 8.6678.667 on (2,12)(2, 12) degrees of freedom. L2 gives q(3,12,0.95)=3.77293q_{(3,12,0.95)} = 3.77293. The standard error of one mean is 2.5/5=0.70711\sqrt{2.5/5} = 0.70711, so HSD=3.77293⋅0.70711=2.6679HSD = 3.77293 \cdot 0.70711 = 2.6679.

pair yˉi−yˉj\bar y_i - \bar y_j qijq_{ij} (L5) adjusted pijp_{ij} (L6) 95% simultaneous interval (L7)
A - B −4-4 5.657 0.004634 [−6.668,−1.332][-6.668, -1.332]
A - C −1-1 1.414 0.5908 [−3.668,1.668][-3.668, 1.668]
B - C 33 4.243 0.02772 [0.332,5.668][0.332, 5.668]

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 2MSE/n\sqrt{2MSE/n}, are q/2q/\sqrt2 for Tukey, (k−1)F(k−1,ν,0.95)\sqrt{(k-1)F_{(k-1,\nu,0.95)}} for Scheffé, t(ν,1−0.025/m)t_{(\nu, 1 - 0.025/m)} for Bonferroni over the mm pairs, and t(ν,0.975)t_{(\nu,0.975)} for the unadjusted t-test:

kk, ν\nu 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, α=0.05\alpha = 0.05, 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 Q4,10Q_{4,10} above qq (seed 4, standard error at most 0.0036):

qq simulated P(Q4,10>q)P(Q_{4,10} > q) 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 q(3,10,0.95)=3.8768q_{(3,10,0.95)} = 3.8768, q(5,5,0.95)=5.6731q_{(5,5,0.95)} = 5.6731, q(4,60,0.95)=3.7371q_{(4,60,0.95)} = 3.7371, q(10,20,0.95)=5.0079q_{(10,20,0.95)} = 5.0079, q(20,120,0.95)=5.1259q_{(20,120,0.95)} = 5.1259, q(3,1,0.95)=26.976q_{(3,1,0.95)} = 26.976 and q(2,∞,0.95)=2.7718=1.959962q_{(2,\infty,0.95)} = 2.7718 = 1.95996\sqrt2.

Correctness

Let all sizes be nn and put Zi=n(yˉi−μi)/σZ_i = \sqrt n(\bar y_i - \mu_i)/\sigma. The ZiZ_i are iid standard normal, and V=ν MSE/σ2V = \nu\,MSE/\sigma^2 is χν2\chi^2_\nu 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 (Zi−Zj)/V/ν(Z_i - Z_j)/\sqrt{V/\nu}, and the largest of them over all pairs is (max⁡Z−min⁡Z)/V/ν=Qk,ν(\max Z - \min Z)/\sqrt{V/\nu} = Q_{k,\nu}. So all intervals cover at once exactly when Qk,ν≤q(k,ν,1−α)Q_{k,\nu} \le q_{(k,\nu,1-\alpha)}, which has probability 1−α1 - \alpha. A false rejection of a true HijH_{ij} means that the interval for μi−μj\mu_i - \mu_j misses, so the family-wise error rate is at most α\alpha for every configuration, and equal to α\alpha when all means are equal. The double integral comes from conditioning on the smallest ZiZ_i and then on V/ν\sqrt{V/\nu}. For two groups Q2,ν=2∣Tν∣Q_{2,\nu} = \sqrt2|T_\nu|, 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 1−α1 - \alpha and the tests control the family-wise error rate at α\alpha in the strong sense. We derive the integral that the helper evaluates, and the exact check for two groups. The model is yij=μi+eijy_{ij} = \mu_i + e_{ij}, i=1,…,ki = 1, \dots, k, j=1,…,nij = 1, \dots, n_i, with iid N(0,σ2)N(0, \sigma^2) errors, N=∑niN = \sum n_i, ν=N−k\nu = N - k, and MSE=SSW/νMSE = SSW/\nu.

Definition. Let Z1,…,ZkZ_1, \dots, Z_k be iid N(0,1)N(0, 1) and V∼χν2V \sim \chi^2_\nu independent of them. The range is R=max⁡iZi−min⁡iZiR = \max_i Z_i - \min_i Z_i, and the studentized range is Qk,ν=R/V/νQ_{k,\nu} = R/\sqrt{V/\nu}. For ν=∞\nu = \infty, Qk,∞=RQ_{k,\infty} = R. q(k,ν,1−α)q_{(k, \nu, 1-\alpha)} is its upper α\alpha point.

Lemma 1 (the law of the range). For w>0w > 0,

P(R≤w)=k∫−∞∞φ(z)(Φ(z+w)−Φ(z))k−1dz,P(R \le w) = k\int_{-\infty}^{\infty}\varphi(z)\big(\Phi(z + w) - \Phi(z)\big)^{k-1}dz,

and, with A(z)=1−Φ(z)A(z) = 1 - \Phi(z),

P(R>w)=k∫−∞∞φ(z)(A(z)k−1−(A(z)−A(z+w))k−1)dz.P(R > w) = k\int_{-\infty}^{\infty}\varphi(z)\Big(A(z)^{k-1} - \big(A(z) - A(z + w)\big)^{k-1}\Big)dz .

Proof. With probability 1 the ZiZ_i are distinct, so exactly one index attains the minimum. R≤wR \le w happens exactly when, for the index ii of the minimum, every other ZjZ_j lies in (Zi,Zi+w](Z_i, Z_i + w]. These kk events are disjoint. Conditioning on Zi=zZ_i = z, the other k−1k - 1 variables are independent with P(z<Zj≤z+w)=Φ(z+w)−Φ(z)P(z < Z_j \le z + w) = \Phi(z + w) - \Phi(z), which gives the first formula after integrating against φ(z)\varphi(z) and adding the kk equal terms. The same argument with w=∞w = \infty gives 1=k∫φ(z)A(z)k−1dz1 = k\int\varphi(z)A(z)^{k-1}dz (some index is the minimum). Subtract the first formula from this and use Φ(z+w)−Φ(z)=A(z)−A(z+w)\Phi(z + w) - \Phi(z) = A(z) - A(z + w). □\square

The helper evaluates the bracket as −Ak−1 expm1((k−1)log⁡(1−r))-A^{k-1}\,\mathrm{expm1}\big((k - 1)\log(1 - r)\big) with r=A(z+w)/A(z)r = A(z + w)/A(z), which is the same number written without the cancellation of two nearly equal powers in the tails.

Lemma 2 (the law of QQ). P(Qk,ν>q)=∫0∞gν(s)P(R>qs)dsP(Q_{k,\nu} > q) = \int_0^\infty g_\nu(s)P(R > qs)ds, where gνg_\nu is the density of S=V/νS = \sqrt{V/\nu}: gν(s)=νν/2Γ(ν/2)2ν/2−1sν−1e−νs2/2g_\nu(s) = \frac{\nu^{\nu/2}}{\Gamma(\nu/2)2^{\nu/2-1}}s^{\nu-1}e^{-\nu s^2/2}.

Proof. RR and SS are independent, so P(R/S>q)=E[P(R>qS∣S)]=∫gν(s)P(R>qs)dsP(R/S > q) = E[P(R > qS \mid S)] = \int g_\nu(s)P(R > qs)ds. The density of SS follows from the χν2\chi^2_\nu density of V=νS2V = \nu S^2 by the change of variables v=νs2v = \nu s^2, dv=2νs dsdv = 2\nu s\,ds. □\square

Lemma 3 (the pivot). Let all ni=nn_i = n. Then

max⁡i<j∣(yˉi−yˉj)−(μi−μj)∣MSE/n∼Qk,ν.\max_{i < j}\frac{\big|(\bar y_i - \bar y_j) - (\mu_i - \mu_j)\big|}{\sqrt{MSE/n}} \sim Q_{k, \nu}.

Proof. Let Zi=n(yˉi−μi)/σZ_i = \sqrt n(\bar y_i - \mu_i)/\sigma. The ZiZ_i are iid N(0,1)N(0, 1), because the groups are independent and each yˉi−μi\bar y_i - \mu_i is the mean of nn iid N(0,σ2)N(0, \sigma^2) errors. V=SSW/σ2∼χν2V = SSW/\sigma^2 \sim \chi^2_\nu 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 ((yˉi−yˉj)−(μi−μj))/MSE/n=(Zi−Zj)/V/ν\big((\bar y_i - \bar y_j) - (\mu_i - \mu_j)\big)/\sqrt{MSE/n} = (Z_i - Z_j)/\sqrt{V/\nu}. The largest ∣Zi−Zj∣|Z_i - Z_j| over pairs is max⁡Z−min⁡Z=R\max Z - \min Z = R. □\square

Lemma 4 (exact simultaneous coverage). With equal sizes the code's interval for μi−μj\mu_i - \mu_j is yˉi−yˉj±q(k,ν,1−α)MSE/n\bar y_i - \bar y_j \pm q_{(k,\nu,1-\alpha)}\sqrt{MSE/n}, and

P(every interval covers its μi−μj)=1−αP\big(\text{every interval covers its } \mu_i - \mu_j\big) = 1 - \alpha

for every μ\mu and σ\sigma.

Proof. The code's standard error is MSE2(1ni+1nj)\sqrt{\frac{MSE}2(\frac1{n_i} + \frac1{n_j})}, which is MSE/n\sqrt{MSE/n} when ni=nj=nn_i = n_j = n. All intervals cover if and only if the maximum in Lemma 3 is at most q(k,ν,1−α)q_{(k,\nu,1-\alpha)}. The law of QQ is continuous, so this has probability exactly 1−α1 - \alpha. □\square

Lemma 5 (strong FWER control). With equal sizes, reject Hij:μi=μjH_{ij}: \mu_i = \mu_j when qij=∣yˉi−yˉj∣/MSE/n>q(k,ν,1−α)q_{ij} = |\bar y_i - \bar y_j|/\sqrt{MSE/n} > q_{(k,\nu,1-\alpha)}, which is the same as pij=P(Q>qij)<αp_{ij} = P(Q > q_{ij}) < \alpha. For every configuration of the means, the probability of rejecting at least one true HijH_{ij} is at most α\alpha, and it equals α\alpha when all kk means are equal.

Proof. If HijH_{ij} is true and rejected, then ∣(yˉi−yˉj)−(μi−μj)∣=∣yˉi−yˉj∣>qMSE/n|(\bar y_i - \bar y_j) - (\mu_i - \mu_j)| = |\bar y_i - \bar y_j| > q\sqrt{MSE/n}, so the interval for μi−μj\mu_i - \mu_j misses. By Lemma 4 the probability that some interval misses is α\alpha. When all means are equal, every HijH_{ij} is true, and some HijH_{ij} is rejected exactly when the maximum in Lemma 3 exceeds qq, which has probability α\alpha. The p-value form is the same event because P(Q>⋅)P(Q > \cdot) is strictly decreasing. □\square

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 k=2k = 2, Q2,ν=2∣T∣Q_{2,\nu} = \sqrt2|T| with T∼tνT \sim t_\nu, and the code's statistic is q12=2∣t∣q_{12} = \sqrt2|t|, where tt is the pooled two-sample t statistic. So P(Q2,ν>q)=P(∣Tν∣>q/2)P(Q_{2,\nu} > q) = P(|T_\nu| > q/\sqrt2).

Proof. R=∣Z1−Z2∣R = |Z_1 - Z_2| and Z1−Z2∼N(0,2)Z_1 - Z_2 \sim N(0, 2), so R=2∣Z∣R = \sqrt2|Z| with Z∼N(0,1)Z \sim N(0,1), and Q=2∣Z∣/V/ν=2∣T∣Q = \sqrt2|Z|/\sqrt{V/\nu} = \sqrt2|T|. For the statistic: the pooled t uses Sp2=MSES_p^2 = MSE and the standard error MSE(1/n1+1/n2)\sqrt{MSE(1/n_1 + 1/n_2)}, while the code divides by MSE2(1/n1+1/n2)\sqrt{\frac{MSE}2(1/n_1 + 1/n_2)}, which is smaller by the factor 2\sqrt2. This holds for unequal sizes as well. □\square

This gives an exact check of the numerical integration, which the tests run for several ν\nu.

What is measured, not proved. The helper computes Lemma 2 by composite Gauss-Legendre rules: 17 panels of 10 nodes on [−8.5,8.5][-8.5, 8.5] for the inner integral and 40 panels of 10 nodes for the outer one, over the range of ss that holds all but 10−3010^{-30} of the chi-square mass. Its error is measured, not bounded: it matches Lemma 6 to 10−1410^{-14} for ν≤30\nu \le 30 and to 10−1210^{-12} for ν\nu up to 1000, it reproduces published table values of q(k,ν,0.95)q_{(k,\nu,0.95)} 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 1−α1 - \alpha; 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 P(Q>q)→0P(Q > q) \to 0 as qq grows. Each tail evaluation is a fixed number of quadrature nodes, 40⋅1040 \cdot 10 outer times 17⋅1017 \cdot 10 inner. The pair loop runs k(k−1)/2k(k-1)/2 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 1−α1 - \alpha, the pairwise tests control the family-wise error rate at exactly α\alpha under the complete null and at most α\alpha 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. ■\blacksquare

Complexity

On a real RAM, L1 makes two passes over the NN observations, Θ(N)\Theta(N). The loop L3 to L7 runs k(k−1)/2k(k-1)/2 times. Each tail evaluation in L6 is a fixed number of quadrature nodes, 400400 outer times 170170 inner, independent of NN and kk, so the loop costs Θ(k2)\Theta(k^2) with a large constant. L2 costs a doubling search and at most 100 false position steps of one tail each. The total time is Θ(N+k2)\Theta(N + k^2), and the extra space is Θ(k2)\Theta(k^2) for the records. In the Python code, one tail takes about 0.02 s and the quantile about 0.3 s.

Numerical stability. MSEMSE 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, A(z)k−1−(A(z)−A(z+w))k−1A(z)^{k-1} - (A(z) - A(z + w))^{k-1} is the difference of two nearly equal powers when ww is large. The code writes it as −Ak−1 expm1((k−1) log1p(−r))-A^{k-1}\,\mathrm{expm1}\big((k-1)\,\mathrm{log1p}(-r)\big) with r=A(z+w)/A(z)r = A(z + w)/A(z), which keeps its relative accuracy. It computes the upper tail directly: for k=2k = 2 and ν=30\nu = 30, a tail of 1.14⋅10−111.14 \cdot 10^{-11} agrees with the exact t tail to a relative error of 2⋅10−92 \cdot 10^{-9}. The check against Q2,ν=2∣Tν∣Q_{2,\nu} = \sqrt2|T_\nu| agrees to 10−1410^{-14} for ν≤30\nu \le 30 and to 10−1210^{-12} for ν\nu up to 1000.

Properties

  • Exact for balanced data. Simultaneous coverage 1−α1 - \alpha and family-wise error rate α\alpha under the complete null, for every nn, kk and σ\sigma.
  • Strong control. The error rate is at most α\alpha under every configuration of the means, not only under the complete null.
  • Two groups. q=2∣t∣q = \sqrt2|t| and Q2,ν=2∣Tν∣Q_{2,\nu} = \sqrt2|T_\nu|, 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 k≥3k \ge 3 (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 MSE2(1ni+1nj)\sqrt{\frac{MSE}2(\frac1{n_i} + \frac1{n_j})} of each pair and the same q(k,ν,1−α)q_{(k,\nu,1-\alpha)} (Kramer, 1956). The code above is already this method. Hayter (1984) proved that its coverage is at least 1−α1 - \alpha, and the simulation above shows rates of 0.0485 and 0.0436. On the one-way ANOVA example with sizes 4, 5 and 6 (MSE=25/12MSE = 25/12), 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 ∑ciμi\sum c_i\mu_i with ∑ci=0\sum c_i = 0: ∑ciyˉi±q(k,ν,1−α)MSE/n⋅12∑∣ci∣\sum c_i\bar y_i \pm q_{(k,\nu,1-\alpha)}\sqrt{MSE/n}\cdot\frac12\sum|c_i|, with simultaneous coverage at least 1−α1 - \alpha. 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 (si2/ni+sj2/nj)/2\sqrt{(s_i^2/n_i + s_j^2/n_j)/2} 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 k−1k - 1 comparisons with one control group are of interest, Dunnett's method uses the maximum of k−1k - 1 correlated t statistics and gives shorter intervals than Tukey's.
  • Stepwise range tests. The Newman-Keuls procedure uses q(p,ν,1−α)q_{(p,\nu,1-\alpha)} for a range of pp ordered means. It does not control the family-wise error rate in the strong sense for k≥4k \ge 4. 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 MSEMSE of that design and its error degrees of freedom.

When to use it

Use Tukey's test when all pairwise comparisons of k≥3k \ge 3 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 MSEMSE is wrong for each pair, and the error rate can be far from α\alpha, 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. pijp_{ij} already accounts for all mm pairs; do not apply another correction to it.
  • The 2\sqrt2 factor. Some tables and programs divide by MSE/n\sqrt{MSE/n} and others by 2MSE/n\sqrt{2MSE/n}. Compare qq with q(k,ν,1−α)q_{(k,\nu,1-\alpha)}, or q/2q/\sqrt2 with q(k,ν,1−α)/2q_{(k,\nu,1-\alpha)}/\sqrt2, never a mixture.
  • Wrong ν\nu or kk. kk is the number of means in the family, not the number of pairs, and ν\nu is the error degrees of freedom of the whole analysis, not ni+nj−2n_i + n_j - 2.
  • 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.

srange.pyI0RawGitHub
# 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

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

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