Algorithmintro
One-way analysis of variance
Also called one-way ANOVA, ANOVA F-test.
Tests whether k group means are equal by the ratio of the between-group to the within-group mean square. Exact F law under normal errors with equal variances. O(N).
- Time
- Θ(n) worst · best
- Space
- Θ(k) extra
- Where
- k = the number of groups; n = the total number of observations, N in the text
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ronald A. Fisher, George W. Snedecor, Bernard L. Welch, 1925
One-way analysis of variance (ANOVA) is a statistical hypothesis test of the null hypothesis that groups have the same mean. It splits the total variation of the data around the grand mean into the variation of the group means around the grand mean (between groups) and the variation of the data around their group means (within groups). It then divides the between mean square by the within mean square. Under normal errors with a common variance, this ratio has the F distribution with and degrees of freedom exactly, for every sample size. With two groups it is the square of the pooled Student t statistic. The test is the regression F-test for the model with one indicator column per group against the model with the intercept only.
In plain words
You have several groups, for example plots under three fertilizers, and you want to know if the true averages differ. The group averages always differ a little, because single plots vary. So compare two kinds of spread. The first is how far the group averages lie from each other. The second is how much single plots scatter inside their own group. If the fertilizers do nothing, both kinds of spread come only from plot-to-plot noise, and their ratio is near one. If the ratio is much larger than one, the group averages are farther apart than the noise explains. Fisher worked out how large the ratio can be by chance when the noise follows a bell curve with the same width in every group. The test says only that some averages differ, not which ones.
The problem
Model. Data for groups () and units , with . The model is , where the errors are iid . The means and the common variance are unknown. In a randomized experiment the groups are the treatments and randomization justifies the comparison.
Hypotheses. against : at least two means differ. The alternative has no direction.
Statistic. With group means , the grand mean , and
the statistic is
The total sum of squares splits as . is the pooled sample variance, an unbiased estimate of whether holds or not. with , so estimates only under .
Null distribution. Exact: under , for every , whatever is. and are squared lengths of the projections of the data onto two orthogonal subspaces, so they are independent scaled chi-square variables (Cochran's theorem in projection form, proved in the correctness proof). Without normality the size is only near ; see the table under Example.
Rejection rule and size. Reject when at , with the lower quantile . The size equals under the model. For example .
p-value. , the upper tail only. Small values of are not evidence against , so there is no doubling.
Sensitivity and power. The test reacts to any spread of the means. Under , has the noncentral F law with noncentrality , and the power depends on the means only through , increasing in it. For three groups of 5 with means and , and the measured power is 0.2255 (4000 replications, seed 8). The test spreads its power over all directions. If one ordered pattern or one contrast is of interest, a test of that contrast has more power. The F-test is uniformly most powerful among tests that are invariant under the natural group of transformations (Lehmann and Romano, Chapter 7).
The algorithm
ONE-WAY-ANOVA(groups y[1..k]) ▷ k ≥ 2, N > k- 1
N ← n[1] + ... + n[k] - 2
for i ← 1 to k: ȳ[i] ← (y[i][1] + ... + y[i][n[i]]) / n[i] - 3
ȳ ← (n[1]·ȳ[1] + ... + n[k]·ȳ[k]) / N - 4
SSB ← Σ_i n[i]·(ȳ[i] - ȳ)² - 5
SSW ← Σ_i Σ_j (y[i][j] - ȳ[i])² ▷ second pass, group mean subtracted first - 6
F ← (SSB / (k - 1)) / (SSW / (N - k)) - 7
p ← F̄(F; k - 1, N - k) ▷ the upper tail of F - 8
return (F, k - 1, N - k, p)
is the upper tail of the F law, where is the regularized incomplete beta function. The shared helper evaluates it by its continued fraction, so a small p-value keeps its digits. If every group is constant, and the code raises an error.
Example
Three groups, , :
| group | data | |||
|---|---|---|---|---|
| A | 5, 7, 6, 8 | 4 | 6.5 | 5 |
| B | 9, 11, 10, 12, 8 | 5 | 10 | 10 |
| C | 6, 8, 7, 5, 9, 7 | 6 | 7 | 10 |
| line | value |
|---|---|
| L3: | |
| L4: | |
| L5: | |
| check: | |
| L6: , | , |
| L6: | |
| L7: |
, so the test rejects equal means at the 5% level. It does not say which groups differ; that is the job of Tukey's test or Scheffé's method. Welch's version on the same data gives on degrees of freedom and .
Two groups. Groups A and B alone give on degrees of freedom and the pooled t statistic , with exactly and the same p-value 0.009167.
Size and power by simulation. Monte Carlo with replications at (standard error of a size near 0.05: 0.0034):
| data | test | measured rejection rate | seed |
|---|---|---|---|
| normal, sizes 5, 5, 5, equal means and variances | F | 0.0510 | 1 |
| normal, sizes 4, 8, 16, | F | 0.0135 | 2 |
| normal, sizes 4, 8, 16, | F | 0.2073 | 3 |
| normal, sizes 8, 8, 8, | F | 0.0658 | 4 |
| normal, sizes 4, 8, 16, | Welch | 0.0608 | 5 |
| normal, sizes 4, 8, 16, | Welch | 0.0495 | 6 |
| exponential, sizes 5, 5, 5, equal means | F | 0.0420 | 7 |
| normal, sizes 5, 5, 5, means 0, 0.5, 1, | F (power) | 0.2255 | 8 |
The F-test keeps its level under skewed errors with equal sizes. With unequal variances and unequal sizes it fails: when the small groups are the noisy ones, is dominated by the quiet large group and the size is 0.21. Welch's test stays near 0.05 in both directions.
Correctness
Let be the projection onto the span of the group indicator vectors and the projection onto the constant vector. Then holds the group means, the grand mean, and . The two projections have orthogonal ranges of dimensions and . Rotating the data into an orthonormal basis adapted to these ranges gives independent normal coordinates, so and are independent chi-square variables, central for always and for under . Their ratio, each divided by its degrees of freedom, is by definition. With two groups, , which gives . The full proofs are in the correctness proof below.
Proof: The one-way ANOVA statistic has the F distribution with (k - 1, N - k) degrees of freedom under the normal nullfull
We prove that the total sum of squares splits into the between and within parts, that the two parts are independent scaled chi-square variables under the normal model, that the F statistic computed by the code has the law under for every sample size, and that with two groups it is the square of the pooled two-sample t statistic. The data are for groups and units , with . Write for the group means, for the grand mean, , and . The model is with the iid .
Lemma 1 (the decomposition). . In vector form, let be the span of the all-ones vector and the span of the group indicator vectors, with orthogonal projections and . Then is the vector that holds at every unit of group , , , , and and are orthogonal projections onto orthogonal subspaces of dimensions and .
Proof. Write and square. The cross term is , because the inner sum is . This gives . For the vector form: the group indicators are orthogonal, the -th has squared norm , so projecting on gives the coefficient on each indicator. In the same way . Because , we have , so and : it is the orthogonal projection onto , of dimension . projects onto , of dimension , and . The squared norms are the two sums by the coordinate formulas above.
Lemma 2 (projections of a normal vector). Let and let and be orthogonal projections with , of ranks and . Then and are independent, with noncentral chi-square laws on and degrees of freedom and noncentralities and . If , the first is central .
Proof. The ranges of and are orthogonal, because . Choose an orthonormal basis of whose first vectors span the range of and whose next vectors span the range of . Let have these rows and set . is orthogonal, so : its coordinates are independent normal variables with variance . Now and are functions of disjoint sets of independent coordinates, so they are independent. A sum of squares of independent variables, divided by , is noncentral with noncentrality , and here . When the noncentrality is 0 the law is central.
This is the projection form of Cochran's theorem. The hat matrix of the one-way model is .
Lemma 3 (the null law). Under the model, for every , and is independent of with noncentral with noncentrality , where . Under , and
Proof. The mean vector lies in , so , and holds at the units of group . Lemma 2 with and (Lemma 1) gives the two laws and the independence. Under , , so . The ratio of two independent chi-square variables, each divided by its degrees of freedom, is by definition, and cancels.
Lemma 4 (the code computes ). Line L1 sets . L2 sets . L3 sets , which is because is the sum of group . L4 and L5 compute and by their definitions, the second with the group mean subtracted before squaring. L6 forms with the degrees of freedom and , and L7 returns .
Proof. Each line is the formula it names, evaluated with exact summation of the terms up to floating point rounding (math.fsum). The code rejects and , where is not defined.
Lemma 5 (size). Under the p-value of L7 is uniform on , so the test "reject when ", which is the test "reject when ", has size exactly . The power is for a noncentral with noncentrality , which increases with .
Proof. has a continuous law with distribution function under (Lemma 3), and . The probability integral transform makes uniform. The two rules are the same event because is strictly decreasing. The power formula is Lemma 3 under . A noncentral chi-square variable with noncentrality is stochastically increasing in : it is with and independent, and increases with for each , because the normal density is symmetric and unimodal.
Lemma 6 ( for two groups). If , then , where is the pooled Student t statistic with . The p-values of the two-sided t-test and of the F-test are equal.
Proof. Let and . Then , so and . So . With and ,
because . If then , and , which is the two-sided p-value.
Termination. The code makes one pass to count, one pass for the group sums, one pass over the means, and one pass for the within-group squares, so it stops after arithmetic operations. The F tail is the incomplete beta continued fraction of the shared helper, which stops at a relative change below or after a fixed cap of iterations.
Theorem. For groups of normal data with a common variance and , the one-way ANOVA code returns , with , and under for every set of sample sizes, so the test has size exactly . With two groups is the square of the pooled t statistic and the two tests agree.
Proof. Lemmas 1 to 6.
The Welch variant in the same file is not covered by this theorem. Its law with estimated degrees of freedom is an approximation, and its size on the page is measured by simulation, not proved.
Complexity
On a real RAM, L2 makes one pass over the values and L5 a second pass; L3 and L4 cost . So the time is , about arithmetic operations, and the extra space is for the group means. The F tail costs a number of continued fraction steps that does not grow with .
Numerical stability. The textbook shortcut subtracts two nearly equal numbers when the data are large compared with their spread, which is catastrophic cancellation. Add to every value of the example: the shortcut gives in double precision instead of 8.336, and with it gives and a division by zero. L5 subtracts the group mean first and returns in both cases. For data that arrive one at a time, the Welford algorithm gives the same accuracy in one pass. L7 computes the upper tail directly, not as one minus the distribution function.
Properties
- Exact under the model. Size for every set of sample sizes, under normal errors with equal variances.
- Invariant. does not change when all data are shifted by a constant or multiplied by a nonzero constant.
- Two groups. , so the test is the two-sided pooled t-test.
- Robust to non-normality, not to unequal variances. With equal or nearly equal group sizes the size stays near for moderate non-normality. With unequal sizes and unequal variances it can be far from in either direction (table above).
- Global. A rejection says that the means are not all equal. It does not say which differ, and the follow-up comparisons need a family-wise error rate control.
- Related to Scheffé. is the largest squared standardized contrast of the group means, so the F-test rejects exactly when some contrast is significant by Scheffé's method.
Variants and improvements
- Welch's test. Welch (1951) weights group by and refers , with , to . Its law is approximate, but its size stays near with unequal variances. With two groups it is the square of the Welch t statistic.
- Rank test. The Kruskal-Wallis test uses the ranks of the pooled data and has an exact null law for continuous data without normality.
- Permutation test. Refer to its distribution over the permutations of the group labels, a permutation test, which is exact under exchangeability.
- Blocks and more factors. Two-way ANOVA adds a second factor, and the randomized block design removes the variation between blocks from the error.
- Random effects. When the groups are a random sample of possible groups, the model with is a linear mixed model. The same F statistic tests , and the variance components are estimated by restricted maximum likelihood or by equating mean squares to their expectations.
- Effect size. is the fraction of the variation explained by the groups, 0.581 in the example. See effect size.
When to use it
Use the F-test as the first test for independent groups when the errors are close to normal and the variances are close to equal, or when the group sizes are equal. Use Welch's test when the variances may differ and the sizes are unequal; many statisticians use it as the default. Use the Kruskal-Wallis test for small samples with clearly non-normal or outlying data. Plan the follow-up comparisons before the data: Tukey's test for all pairs, Scheffé's method for any contrasts chosen after looking at the data, and the Bonferroni correction for a few planned contrasts.
Pitfalls
- Unequal variances with unequal sizes. The size can be 0.21 or 0.014 instead of 0.05 (table above).
- Many t-tests instead of one ANOVA. Testing every pair at level makes the chance of at least one false rejection grow with ; this is the multiple comparisons problem.
- Reading a rejection as "all means differ". The alternative is only that some means differ.
- Using the shortcut formula. The one-pass formula for cancels catastrophically for large, nearly equal values.
- Dependent observations. Repeated measures on the same subject, or plots in the same field block, break the independence of the errors. Use a randomized block design analysis or a linear mixed model.
- A non-significant F as proof of equal means. It shows only that the data cannot rule out equal means; check the statistical power.
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
# Part of https://algorithm.tamnd.com/one-way-anova/. The authors are listed in prov/QHQ1W6.jsonl.
"""One-way analysis of variance, and Welch's heteroscedastic version.
one_way_anova splits the total sum of squares into the part between the group
means and the part within the groups, and refers the ratio of their mean
squares to the F distribution with (k - 1, N - k) degrees of freedom. Each
group sum of squares uses the two-pass formula (subtract the group mean
first), which does not cancel like sum y^2 - n ybar^2. The p-value comes from
the upper tail f_sf directly, not from 1 - cdf.
welch_anova is Welch's (1951) test, which weights each group by n_i / s_i^2
and does not assume equal variances. With two groups its statistic is the
square of the Welch t statistic.
"""
import math
from collections.abc import Sequence
from typing import NamedTuple
from stdist import f_sf
class AnovaResult(NamedTuple):
f: float # the F statistic
df1: int # k - 1
df2: int # N - k
p: float # P(F_(df1, df2) > f)
ssb: float # sum of squares between groups
ssw: float # sum of squares within groups
means: list[float]
def one_way_anova(groups: Sequence[Sequence[float]]) -> AnovaResult:
"""Test H_0: all k group means are equal, for normal groups with a common variance."""
k = len(groups)
if k < 2 or any(len(g) == 0 for g in groups):
raise ValueError("need at least two nonempty groups")
n = [len(g) for g in groups]
big_n = sum(n) # @line L1
if big_n <= k:
raise ValueError("need N > k, so that some group has two or more values")
means = [math.fsum(g) / len(g) for g in groups] # @line L2
grand = math.fsum(ni * m for ni, m in zip(n, means)) / big_n # @line L3
ssb = math.fsum(ni * (m - grand) ** 2 for ni, m in zip(n, means)) # @line L4
ssw = math.fsum((v - m) ** 2 for g, m in zip(groups, means) for v in g) # @line L5
if ssw == 0.0:
raise ValueError("every group is constant, so the within mean square is 0")
df1, df2 = k - 1, big_n - k
f = (ssb / df1) / (ssw / df2) # @line L6
p = f_sf(f, df1, df2) # @line L7
return AnovaResult(f, df1, df2, p, ssb, ssw, means) # @line L8
def welch_anova(groups: Sequence[Sequence[float]]) -> tuple[float, float, float, float]:
"""Welch's test of equal means without equal variances: (F*, df1, df2, p)."""
k = len(groups)
if k < 2 or any(len(g) < 2 for g in groups):
raise ValueError("need at least two groups of two or more values")
n = [len(g) for g in groups]
means = [math.fsum(g) / len(g) for g in groups]
var = [math.fsum((v - m) ** 2 for v in g) / (len(g) - 1) for g, m in zip(groups, means)]
if any(v == 0.0 for v in var):
raise ValueError("a group is constant, so its weight n / s^2 is infinite")
w = [ni / v for ni, v in zip(n, var)]
total_w = math.fsum(w)
mw = math.fsum(wi * m for wi, m in zip(w, means)) / total_w
a = math.fsum(wi * (m - mw) ** 2 for wi, m in zip(w, means)) / (k - 1)
lam = math.fsum((1.0 - wi / total_w) ** 2 / (ni - 1) for wi, ni in zip(w, n))
f = a / (1.0 + 2.0 * (k - 2) / (k * k - 1) * lam)
df2 = (k * k - 1) / (3.0 * lam)
return f, k - 1, df2, f_sf(f, k - 1, df2)
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)
test_one_way_anova.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/one-way-anova/. The authors are listed in prov/QHQ1W6.jsonl.
import math
import random
from fractions import Fraction
import pytest
from one_way_anova import one_way_anova, welch_anova
from stdist import f_ppf, t_sf
EXAMPLE = [[5, 7, 6, 8], [9, 11, 10, 12, 8], [6, 8, 7, 5, 9, 7]]
def exact_sums(groups: list[list[int]]) -> tuple[Fraction, Fraction, Fraction]:
"""SSB, SSW and SST from their definitions, in exact arithmetic."""
big_n = sum(len(g) for g in groups)
grand = Fraction(sum(sum(g) for g in groups), big_n)
means = [Fraction(sum(g), len(g)) for g in groups]
ssb = sum(len(g) * (m - grand) ** 2 for g, m in zip(groups, means))
ssw = sum((v - m) ** 2 for g, m in zip(groups, means) for v in g)
sst = sum((v - grand) ** 2 for g in groups for v in g)
return ssb, ssw, sst
def test_example() -> None:
r = one_way_anova(EXAMPLE)
ssb, ssw, sst = exact_sums(EXAMPLE)
assert (ssb, ssw, sst) == (Fraction(521, 15), Fraction(25), Fraction(896, 15))
assert ssb + ssw == sst
assert (r.df1, r.df2) == (2, 12)
assert r.means == [6.5, 10.0, 7.0]
assert abs(r.ssb - 521 / 15) < 1e-12 and abs(r.ssw - 25.0) < 1e-12
assert abs(r.f - 1042 / 125) < 1e-12
assert abs(r.p - 0.005374518329892695) < 1e-12
assert r.f > f_ppf(0.95, 2, 12)
def test_decomposition_against_fractions() -> None:
rng = random.Random(1)
for _ in range(200):
k = rng.randint(2, 6)
groups = [[rng.randint(-50, 50) for _ in range(rng.randint(1, 7))] for _ in range(k)]
if sum(len(g) for g in groups) <= k:
continue
ssb, ssw, sst = exact_sums(groups)
assert ssb + ssw == sst
if ssw == 0:
continue
r = one_way_anova(groups)
df2 = sum(len(g) for g in groups) - k
f = (ssb / (k - 1)) / (ssw / df2)
assert abs(r.ssb - float(ssb)) <= 1e-9 * max(1.0, float(sst))
assert abs(r.ssw - float(ssw)) <= 1e-9 * max(1.0, float(sst))
assert abs(r.f - float(f)) <= 1e-9 * max(1.0, float(f))
def test_two_groups_f_is_t_squared() -> None:
rng = random.Random(2)
for _ in range(100):
x = [rng.randint(0, 30) for _ in range(rng.randint(1, 8))]
y = [rng.randint(0, 30) for _ in range(rng.randint(2, 8))]
mx, my = Fraction(sum(x), len(x)), Fraction(sum(y), len(y))
ss = sum((v - mx) ** 2 for v in x) + sum((v - my) ** 2 for v in y)
if ss == 0:
continue
sp2 = ss / (len(x) + len(y) - 2)
t2 = (mx - my) ** 2 / (sp2 * (Fraction(1, len(x)) + Fraction(1, len(y))))
assert exact_sums([x, y])[0] / (sp2) == t2 # SSB / MSE = t^2, exactly
r = one_way_anova([x, y])
assert abs(r.f - float(t2)) <= 1e-10 * max(1.0, float(t2))
assert abs(r.p - 2.0 * t_sf(math.sqrt(r.f), len(x) + len(y) - 2)) < 1e-12
def test_shift_does_not_cancel() -> None:
shifted = [[1e9 + v for v in g] for g in EXAMPLE]
assert abs(one_way_anova(shifted).f - 8.336) < 1e-6
def test_size_under_the_null() -> None:
rng = random.Random(3)
reps, alpha = 3000, 0.05
rej = sum(one_way_anova([[rng.gauss(0.0, 1.0) for _ in range(n)] for n in (4, 6, 9)]).p <= alpha
for _ in range(reps))
se = math.sqrt(alpha * (1 - alpha) / reps)
assert abs(rej / reps - alpha) < 4.0 * se
def test_welch_two_groups_is_welch_t_squared() -> None:
rng = random.Random(4)
for _ in range(50):
x = [rng.gauss(0.0, 1.0) for _ in range(rng.randint(2, 9))]
y = [rng.gauss(0.5, 3.0) for _ in range(rng.randint(2, 9))]
mx, my = sum(x) / len(x), sum(y) / len(y)
a = sum((v - mx) ** 2 for v in x) / (len(x) - 1) / len(x)
b = sum((v - my) ** 2 for v in y) / (len(y) - 1) / len(y)
t2 = (mx - my) ** 2 / (a + b)
df = (a + b) ** 2 / (a * a / (len(x) - 1) + b * b / (len(y) - 1))
f, df1, df2, p = welch_anova([x, y])
assert df1 == 1
assert abs(f - t2) <= 1e-10 * t2 and abs(df2 - df) <= 1e-10 * df
assert abs(p - 2.0 * t_sf(math.sqrt(t2), df)) < 1e-12
def test_welch_example() -> None:
f, df1, df2, p = welch_anova(EXAMPLE)
assert df1 == 2
assert abs(f - 7.110393149302828) < 1e-9
assert abs(df2 - 7.490339568443729) < 1e-9
assert abs(p - 0.01858036702427885) < 1e-9
def test_errors() -> None:
with pytest.raises(ValueError):
one_way_anova([[1.0, 2.0]])
with pytest.raises(ValueError):
one_way_anova([[1.0], [2.0]])
with pytest.raises(ValueError):
one_way_anova([[1.0, 1.0], [2.0, 2.0]])
test_stdist.py 60 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
import math
from stdist import (
beta_inc, chi2_cdf, chi2_ppf, chi2_sf, f_cdf, f_ppf, f_sf, gamma_p, gamma_q,
norm_cdf, norm_ppf, norm_sf, t_cdf, t_ppf, t_sf,
)
XS = [0.001, 0.01, 0.1, 0.3, 0.5, 1.0, 1.7, 2.5, 4.0, 7.0, 12.0, 30.0, 80.0]
def test_chi2_two_degrees_of_freedom() -> None:
for x in XS:
assert abs(chi2_cdf(x, 2) - (1.0 - math.exp(-x / 2.0))) < 1e-13
assert abs(chi2_sf(x, 2) - math.exp(-x / 2.0)) <= 1e-12 * math.exp(-x / 2.0)
def test_t_one_and_two_degrees_of_freedom() -> None:
for x in XS + [-v for v in XS] + [0.0]:
assert abs(t_cdf(x, 1) - (0.5 + math.atan(x) / math.pi)) < 1e-13
assert abs(t_cdf(x, 2) - (0.5 + x / (2.0 * math.sqrt(2.0 + x * x)))) < 1e-13
assert abs(t_cdf(x, 3) + t_sf(x, 3) - 1.0) < 1e-14
def test_f_is_square_of_t() -> None:
for k in [1, 2, 3, 5, 10, 30]:
for x in XS:
two_sided = 2.0 * t_sf(math.sqrt(x), k)
assert abs(f_sf(x, 1, k) - two_sided) < 1e-13
assert abs(f_cdf(x, 1, k) + f_sf(x, 1, k) - 1.0) < 1e-14
def test_gamma_and_beta_identities() -> None:
for a in [0.5, 1.0, 2.5, 10.0, 50.0]:
for x in XS:
assert abs(gamma_p(a, x) + gamma_q(a, x) - 1.0) < 1e-14
# P(1, x) = 1 - e^(-x); I_x(a, 1) = x^a; I_x(1, b) = 1 - (1 - x)^b.
for x in [0.05, 0.3, 0.5, 0.8, 0.99]:
assert abs(gamma_p(1.0, x) - (1.0 - math.exp(-x))) < 1e-14
for a in [0.5, 2.0, 7.0]:
assert abs(beta_inc(a, 1.0, x) - x**a) < 1e-13
assert abs(beta_inc(1.0, a, x) - (1.0 - (1.0 - x) ** a)) < 1e-13
def test_upper_tails_do_not_cancel() -> None:
assert abs(norm_sf(10.0) / 7.619853024160527e-24 - 1.0) < 1e-12
assert abs(chi2_sf(200.0, 2) / math.exp(-100.0) - 1.0) < 1e-12
assert norm_cdf(-30.0) > 0.0
def test_quantiles() -> None:
assert abs(norm_ppf(0.975) - 1.959963985) < 1e-8
assert abs(chi2_ppf(0.95, 1) - 3.841458821) < 1e-8
assert abs(t_ppf(0.975, 10) - 2.228138852) < 1e-8
for p in [1e-6, 0.01, 0.2, 0.5, 0.8, 0.99, 1.0 - 1e-6]:
for k in [1, 4, 25]:
assert abs(chi2_cdf(chi2_ppf(p, k), k) - p) < 1e-12
assert abs(t_cdf(t_ppf(p, k), k) - p) < 1e-12
assert abs(f_cdf(f_ppf(p, k, 7), k, 7) - p) < 1e-12
History
Ronald A. Fisher introduced the word "variance" in 1918 and developed the analysis of variance at Rothamsted Experimental Station for agricultural field trials. Statistical Methods for Research Workers (1925) presented the method with tables for . George W. Snedecor tabulated the variance ratio itself and named it F in honor of Fisher in 1934. Bernard L. Welch gave the test without equal variances in 1951.
References
- Ronald A. Fisher, Statistical Methods for Research Workers, Oliver and Boyd, 1925, online text of the first edition, Chapter VII (intraclass correlations and the analysis of variance)
- B. L. Welch, On the comparison of several mean values: an alternative approach, Biometrika 38(3-4), 1951, pp. 330 to 336 (the weighted statistic and its approximate F law with estimated denominator degrees of freedom)
- George Casella and Roger L. Berger, Statistical Inference, second edition, Duxbury, 2002, Section 11.2 (oneway analysis of variance, the F-test, contrasts and the partition of sums of squares)
- Douglas C. Montgomery, Design and Analysis of Experiments, tenth edition, Wiley, 2019, Chapter 3 (experiments with a single factor, the analysis of variance, model adequacy checking)
- George A. F. Seber and Alan J. Lee, Linear Regression Analysis, second edition, Wiley, 2003, Chapter 2 (quadratic forms of normal vectors, Cochran's theorem) and Chapter 8 (analysis of variance; chapter-level locators)
- E. L. Lehmann and Joseph P. Romano, Testing Statistical Hypotheses, third edition, Springer, 2005, Chapter 7 (linear hypotheses, the F-test as a UMP invariant test; chapter-level locator)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag QHQ1W6 Edit this page History Report an error Markdown