Overview
ANOVA tells you that the group means are not all equal. It does not say which groups differ. The natural next step is to compare every pair, but each comparison is another chance for a false alarm, and with groups there are pairs. Post-hoc tests keep the family-wise error rate, the chance of at least one false alarm across all pairs, at . Bonferroni does it bluntly, by multiplying every pair's p-value by the number of pairs. Tukey's HSD (honestly significant difference) does it exactly for the all-pairs case, by using the distribution of the largest gap among means. Both estimate noise with the pooled within-group mean square from the ANOVA.
A short history
A significant ANOVA says that some means differ but not which. John Tukey answered this in 1949 with a procedure based on the studentised range, later known as the honestly significant difference, which keeps the error rate for the whole set of pairwise comparisons at alpha. The Bonferroni correction rests on inequalities published by Carlo Emilio Bonferroni in 1936; Olive Jean Dunn showed in 1961 how to apply it to multiple comparisons.
How it works
- Compute every group mean and the pooled within-group mean square with degrees of freedom.
- For each pair, take the difference of the two means and its standard error from and the two group sizes.
- Tukey: divide the absolute difference by the standard error to get and take the p-value from the studentized range distribution for means.
- Bonferroni: form an ordinary pooled statistic and multiply its two-sided p-value by the number of pairs, capping at 1.
- Build a simultaneous confidence interval for each difference from the method's critical value.
- Mark a pair as different when its adjusted p-value is below , which is the same as its interval excluding zero.
Watch out for
- Bonferroni is conservative: with many pairs the cutoff becomes so strict that real differences are missed. For all pairs Tukey is tighter.
- Both methods pool one variance across all groups. If one group is far noisier, the standard error is wrong for every pair that involves it.
- The template finds studentized range probabilities by numerical integration on a fixed grid, which is accurate enough for teaching but is not a replacement for a statistics library's tables at extreme tails.
- Results can look inconsistent, for example A equals B and B equals C but A differs from C. That is a statement about evidence, not about equality.
Use cases
When to use it
After a significant ANOVA, when you need to say which specific groups differ. Use Tukey for all pairwise comparisons and Bonferroni when you care about only a few planned ones.
In industry
- Clinical research
- After a trial with several dose groups shows an overall effect, pairwise comparisons with adjusted cutoffs identify which doses differ from each other.
- Agriculture
- Variety trials report Tukey groupings, so that growers can see which varieties are statistically indistinguishable.
- Genomics
- Studies that test many genes or variants use Bonferroni style thresholds, such as the genome wide significance level, to limit false discoveries.
Choosing it: what must hold
- A set of group means to compare, normally after an ANOVA on the same data.
- For Tukey HSD, all pairwise comparisons with roughly equal variances; the Tukey-Kramer form handles unequal group sizes.
- For Bonferroni, a known number of planned comparisons, ideally small.
- Agreement that controlling the chance of any false alarm in the family is the right goal.
When to choose something else
| If | Use instead |
|---|---|
| Every group is compared only with a control | Dunnett's test |
| Variances are unequal across groups | The Games-Howell procedure |
| There are hundreds or thousands of tests and some false positives are tolerable | False discovery rate control with Benjamini-Hochberg |
| You want more power than Bonferroni for the same guarantee | The Holm step down procedure |
Math foundations
Number of comparisons and the problem
With groups there are pairs. If each is tested at level , the chance of some false alarm can be as large as . Both methods exist to pull this back down to .
Pooled noise estimate
The within-group mean square from the ANOVA table. Every pairwise comparison uses it, so each one borrows information about the noise from all groups.
Bonferroni
An ordinary statistic on degrees of freedom, with its two-sided p-value multiplied by the number of pairs. This is the same as testing each pair at level .
Tukey's statistic
The gap between two means in units of the standard error of a single mean. With equal sizes the denominator is . With unequal sizes this is the Tukey-Kramer form. Note that .
Tukey's reference distribution
is the studentized range: the largest gap among sample means from one population, over an independent estimate of their standard error. Comparing every pair with the largest possible gap is what controls the error rate over all pairs at once.
Simultaneous intervals
Here is the method's critical value and the matching denominator above. For Tukey is the quantile of , for Bonferroni the quantile of . All intervals cover their true differences together with probability about .
Symbols
- number of groups
- number of pairwise comparisons
- size of group i
- total number of values
- mean of group i
- within-group mean square
- Bonferroni and Tukey statistics for the pair (i, j)
- unadjusted two-sided p-value of the pair
- studentized range of k means with error degrees of freedom nu
- sample means from one common population and an independent estimate of its standard deviation
- critical value and standard error used in the interval
- family-wise significance level
Worked by hand
Three groups of three: , , with means 2, 3, 7. From the one-way ANOVA, on 6 degrees of freedom. The 5% critical value of the studentized range for 3 means and 6 degrees of freedom is 4.34.
Groups 1 and 2 are not distinguishable (). Group 3 differs from both. Any two means more than 2.51 apart are declared different.
Visual example
Loading the example.
Try this
- Switch between Tukey HSD and Bonferroni and compare the critical gap in the readout.
- Raise the number of groups from 3 to 5 with the same spacing: every interval widens.
- Set the distance between means to 0. Any pair that is still flagged is a false alarm.
Code sample
from impl import PostHoc
from config import PostHocConfig
groups = [[6, 8, 4, 5, 3, 4], [8, 12, 9, 11, 6, 8], [13, 9, 11, 8, 7, 12]]
result = PostHoc(PostHocConfig(method="tukey", alpha=0.05)).fit(groups)
for c in result["comparisons"]:
print(c["i"], c["j"], round(c["mean_diff"], 2), round(c["p_value"], 4), c["reject"])Read the implementation (185 lines)
"""Post-hoc pairwise comparisons after a one-way ANOVA: Tukey's HSD and Bonferroni.
NumPy and the standard library only. Student's t comes from the regularized incomplete beta function and the
studentized range distribution from numerical integration, both defined in this file.
"""
from __future__ import annotations
import functools
import math
import numpy as np
try:
from .config import PostHocConfig
except ImportError: # run from the template's own folder
from config import PostHocConfig
def _betacf(a: float, b: float, x: float) -> float:
"""Continued fraction of the incomplete beta function (modified Lentz method)."""
tiny = 1e-300
qab, qap, qam = a + b, a + 1.0, a - 1.0
c = 1.0
d = 1.0 - qab * x / qap
d = 1.0 / (d if abs(d) > tiny else tiny)
h = d
for m in range(1, 2000):
m2 = 2 * m
for aa in (
m * (b - m) * x / ((qam + m2) * (a + m2)),
-(a + m) * (qab + m) * x / ((a + m2) * (qap + m2)),
):
d = 1.0 + aa * d
d = 1.0 / (d if abs(d) > tiny else tiny)
c = 1.0 + aa / c
c = c if abs(c) > tiny else tiny
delta = d * c
h *= delta
if abs(delta - 1.0) < 1e-15:
break
return h
def betainc(a: float, b: float, x: float) -> float:
"""Regularized incomplete beta function I_x(a, b), for a, b > 0 and 0 <= x <= 1."""
if x <= 0.0:
return 0.0
if x >= 1.0:
return 1.0
front = math.exp(
math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log1p(-x)
)
if x < (a + 1.0) / (a + b + 2.0):
return front * _betacf(a, b, x) / a
return 1.0 - front * _betacf(b, a, 1.0 - x) / b
def t_cdf(t: float, df: float) -> float:
"""P(T <= t) for Student's t with `df` degrees of freedom."""
tail = 0.5 * betainc(0.5 * df, 0.5, df / (df + t * t))
return 1.0 - tail if t > 0 else tail
def t_sf(t: float, df: float) -> float:
"""P(T > t) for Student's t with `df` degrees of freedom."""
return t_cdf(-t, df)
def _bisect(fn, lo: float, hi: float) -> float:
"""Root of the increasing function `fn` on [lo, hi], by bisection."""
for _ in range(100):
mid = 0.5 * (lo + hi)
if fn(mid) < 0.0:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
def t_ppf(p: float, df: float) -> float:
"""Quantile of Student's t: the t with P(T <= t) = p, for 0 < p < 1."""
if not 0.0 < p < 1.0:
raise ValueError(f"p must be in (0, 1), got {p}")
if p > 0.5:
return -t_ppf(1.0 - p, df)
lo = -1.0
while t_cdf(lo, df) > p:
lo *= 2.0
return _bisect(lambda t: t_cdf(t, df) - p, lo, 0.0)
_Z = np.linspace(-8.0, 8.0, 321) # integration grid for a standard normal value
_Z_WEIGHT = np.exp(-0.5 * _Z**2) / math.sqrt(2.0 * math.pi) * (_Z[1] - _Z[0])
_PHI_X = np.linspace(-14.0, 14.0, 28001) # lookup table of the normal CDF, interpolated linearly
_PHI_Y = np.array([0.5 * math.erfc(-v / math.sqrt(2.0)) for v in _PHI_X])
_PHI_Z = np.interp(_Z, _PHI_X, _PHI_Y) # the normal CDF on the integration grid
def _normal_range_cdf(w: np.ndarray, k: int) -> np.ndarray:
"""P(max - min of k independent standard normals <= w). w: (m,), returns (m,).
Uses P = k * integral of pdf(z) * (cdf(z) - cdf(z - w))^(k - 1) dz, where z is the largest value.
"""
spread = _PHI_Z[None, :] - np.interp(_Z[None, :] - w[:, None], _PHI_X, _PHI_Y) # (m, len(_Z))
return k * (spread ** (k - 1)) @ _Z_WEIGHT
def studentized_range_cdf(q: float, k: int, df: float) -> float:
"""P(Q <= q) for the studentized range of k means with `df` error degrees of freedom.
Q = (largest mean - smallest mean) / (s / sqrt(n)). The normal range CDF is averaged over the
distribution of s / sigma, which is sqrt(chi-square(df) / df).
"""
if q <= 0.0:
return 0.0
half_width = 12.0 / math.sqrt(2.0 * df)
s = np.linspace(max(1e-9, 1.0 - half_width), 1.0 + half_width, 101)
log_density = (0.5 * df * math.log(df) - math.lgamma(0.5 * df) - (0.5 * df - 1.0) * math.log(2.0)
+ (df - 1.0) * np.log(s) - 0.5 * df * s * s)
y = np.exp(log_density) * _normal_range_cdf(q * s, k)
return float(min(1.0, np.sum(0.5 * (y[1:] + y[:-1])) * (s[1] - s[0])))
@functools.lru_cache(maxsize=256)
def studentized_range_ppf(p: float, k: int, df: float) -> float:
"""The q with P(Q <= q) = p: the critical value found in studentized range tables."""
if not 0.0 < p < 1.0:
raise ValueError(f"p must be in (0, 1), got {p}")
lo, hi = 0.0, 8.0
while studentized_range_cdf(hi, k, df) < p:
hi *= 2.0
for _ in range(50):
mid = 0.5 * (lo + hi)
if studentized_range_cdf(mid, k, df) < p:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
class PostHoc:
"""Compares every pair of group means while keeping the family-wise error rate at alpha."""
def __init__(self, config: PostHocConfig | None = None) -> None:
self.config = config or PostHocConfig()
def fit(self, groups) -> dict:
"""Compare all pairs.
groups: a sequence of k >= 2 one-dimensional samples, shapes (n_1,), ..., (n_k,).
Returns a dict with `ms_within`, `df_within`, `critical_value` (of q for Tukey, of |t| for
Bonferroni) and `comparisons`: one dict per pair i < j with `i`, `j`, `mean_diff`
(mean_i - mean_j), `statistic`, `p_value` (already adjusted), `ci_low`, `ci_high` (simultaneous
1 - alpha interval for the difference) and `reject`.
"""
samples = [np.asarray(g, dtype=float).ravel() for g in groups]
k = len(samples)
if k < 2:
raise ValueError("need at least 2 groups")
if any(s.size < 2 for s in samples):
raise ValueError("every group needs at least 2 values")
sizes = [s.size for s in samples]
means = [float(s.mean()) for s in samples]
df = sum(sizes) - k
ms_within = float(sum(np.sum((s - m) ** 2) for s, m in zip(samples, means))) / df
if ms_within <= 0.0:
raise ValueError("the within-group variance is zero, nothing to compare against")
n_pairs = k * (k - 1) // 2
alpha = self.config.alpha
tukey = self.config.method == "tukey"
critical = studentized_range_ppf(1.0 - alpha, k, df) if tukey else t_ppf(1.0 - alpha / (2 * n_pairs), df)
comparisons = []
for i in range(k):
for j in range(i + 1, k):
diff = means[i] - means[j]
spread = ms_within * (1.0 / sizes[i] + 1.0 / sizes[j])
if tukey:
se = math.sqrt(spread / 2.0)
stat = abs(diff) / se
p = 1.0 - studentized_range_cdf(stat, k, df)
else:
se = math.sqrt(spread)
stat = diff / se
p = min(1.0, n_pairs * 2.0 * t_cdf(-abs(stat), df))
comparisons.append({
"i": i, "j": j, "mean_diff": diff, "statistic": stat, "p_value": max(p, 0.0),
"ci_low": diff - critical * se, "ci_high": diff + critical * se,
"reject": p < alpha,
})
return {"method": self.config.method, "ms_within": ms_within, "df_within": df,
"critical_value": critical, "comparisons": comparisons}- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
Call PostHoc().fit(groups) on the three groups from the worked example and compare each statistic and the critical_value with the hand calculation. Then refit with PostHocConfig(method="bonferroni") and compare the adjusted p_value and the width of ci_low to ci_high for each pair between the two methods.
Check on learning
- With 10 groups, how many pairs are there and what per-pair level does Bonferroni use at ? What does that do to the power to detect a moderate difference?
A way to think about it
Compute and , then think about how far out in the tail of the distribution that cutoff sits.
- Why does Tukey's method refer each pair to the distribution of the largest gap among all means, even for a pair whose gap is small?
A way to think about it
The guarantee is about the whole family. If the largest gap rarely exceeds the cutoff by chance, ask what that implies for every smaller gap.
- You planned in advance to compare only two specific pairs out of ten groups. Which method is likely to give narrower intervals, and why?
A way to think about it
Bonferroni pays for the number of comparisons you actually make. Tukey always pays for all of them.
- An ANOVA is significant but no Tukey pair is. Is one of the two results wrong?
A way to think about it
The test responds to any pattern among the means, including contrasts such as one group against the average of the rest. Pairwise tests look only at pairs.