Algorithm Search⌘K

Algorithmcore

Kruskal-Wallis test

Also called Kruskal-Wallis H test, one-way ANOVA on ranks.

Extends the Mann-Whitney test to k groups by comparing the mean ranks of the groups in the pooled sample. The statistic is roughly chi-squared with k - 1 degrees of freedom.

Time
Θ(N log N) worst · best
Space
Θ(N) extra
Where
N = the total number of observations; k = the number of groups
Properties
deterministicnot exactofflineiterative
Origin
William H. Kruskal, W. Allen Wallis, 1952

The Kruskal-Wallis test compares k≥2k \ge 2 independent groups. It ranks all NN observations together, computes the mean rank of each group, and measures how far these means are from the overall mean rank (N+1)/2(N + 1)/2. The statistic HH is the one-way analysis of variance F idea applied to ranks: up to a constant, it is the between-group sum of squares of the ranks. Under the null hypothesis that all groups come from one distribution, HH is approximately chi-square with k−1k - 1 degrees of freedom; its exact law, given the ranks, comes from counting all ways to split the ranks into groups of the given sizes. For k=2k = 2 it is the two-sided Mann-Whitney test.

In plain words

Several groups of students learn by different methods and then take one test. Put all the scores in one list, sort it, and give each student a place number. If the methods do not matter, each group should get a fair mix of low and high place numbers, so the average place number of every group should be near the middle.

The test adds up how far each group's average place is from the middle, giving bigger groups more weight. A large total means some group sits mostly at the top or the bottom of the list. The test then asks how often a total this large would appear if the group labels were handed out at random.

The problem

Model. There are kk groups. Group ii has ni≥1n_i \ge 1 observations Xi1,…,XiniX_{i1}, \ldots, X_{i n_i}, independent with distribution FiF_i, and the groups are independent. N=n1+⋯+nkN = n_1 + \cdots + n_k.

Hypotheses. H0H_0: F1=⋯=FkF_1 = \cdots = F_k. The alternative is that the FiF_i are not all equal. The test is designed for, and consistent against, alternatives where some group tends to give larger or smaller values than the others, such as a location shift Fi(t)=F(t−θi)F_i(t) = F(t - \theta_i) with not all θi\theta_i equal.

Statistic. Rank the pooled sample from 11 to NN, with midranks for ties. Let RiR_i be the rank sum and Rˉi=Ri/ni\bar R_i = R_i / n_i the mean rank of group ii. Then

H′=12N(N+1)∑i=1kni(Rˉi−N+12)2=12N(N+1)∑i=1kRi2ni−3(N+1),H' = \frac{12}{N(N+1)} \sum_{i=1}^{k} n_i \left(\bar R_i - \frac{N+1}{2}\right)^2 = \frac{12}{N(N+1)} \sum_{i=1}^{k} \frac{R_i^2}{n_i} - 3(N + 1),

and the tie-corrected statistic is H=H′/CH = H' / C with C=1−∑j(tj3−tj)/(N3−N)C = 1 - \sum_j (t_j^3 - t_j)/(N^3 - N), where tjt_j are the sizes of the tie groups. With midranks, H=(N−1) SSB/SSTH = (N - 1)\, SS_B / SS_T, where SSBSS_B and SSTSS_T are the between-group and total sums of squares of the ranks.

Null distribution. Under H0H_0 the pooled sample is exchangeable, so given the pooled values every split of the NN positions into groups of sizes n1,…,nkn_1, \ldots, n_k has probability n1!⋯nk!/N!n_1! \cdots n_k! / N!. This conditional law of HH is exact. As min⁡ini→∞\min_i n_i \to \infty, HH converges in law to chi-square with k−1k - 1 degrees of freedom, with or without ties (asymptotic).

P-values. The test is one-sided in HH: large values are evidence against H0H_0. The asymptotic p-value is P(χk−12≥H)P(\chi^2_{k-1} \ge H). The exact p-value is the share of splits whose HH is at least the observed value. There is no two-sided version; HH already measures departures in every direction.

Rejection rule and size. Reject at level α\alpha when p≤αp \le \alpha. The exact p-value gives size at most α\alpha. The chi-square p-value is only approximate: for three groups of 3 the exact 5% critical value is 5.65.6 against the chi-square value 5.9915.991, and P(H≥5.991)=18/1680=0.0107P(H \ge 5.991) = 18/1680 = 0.0107, so the chi-square test is conservative there.

Sensitivity and power. For a location shift the efficiency against one-way ANOVA is 3/π≈0.9553/\pi \approx 0.955 for normal errors and at least 0.8640.864 for every continuous law, as for the Mann-Whitney test. A Monte Carlo run with three groups of 10, a shift of 1 in one group, r=2000r = 2000 samples per law and α=0.05\alpha = 0.05 gave power 0.5410.541 for the Kruskal-Wallis test against 0.5860.586 for ANOVA with normal errors (seed 41), and 0.1840.184 against 0.0500.050 with Cauchy errors (seed 42).

The algorithm

  1. KRUSKAL-WALLIS(groups X_1, ..., X_k, method)
  2. 1r ← midranks of the pooled sample, computed after one sort
  3. 2R_i ← sum of r over group i, for i = 1, ..., k
  4. 3H' ← 12 / (N(N + 1)) · (R_1^2 / n_1 + ... + R_k^2 / n_k) - 3(N + 1)
  5. 4C ← 1 - Σ_j (t_j^3 - t_j) / (N^3 - N); H ← H' / C
  6. 5if method = asymptotic then return H, P(χ²_{k-1} ≥ H)
  7. 6count all splits of the pooled ranks into groups of sizes n_1, ..., n_k, by their rank sums
  8. 7A ← number of splits with Σ_i R_i^2 / n_i ≥ the observed value
  9. 8return H, A · n_1! ··· n_k! / N!

The code computes HH as an exact fraction from doubled midranks, so it has no rounding error, and evaluates the chi-square tail with the shared stdist.py. For the exact method, line L6 is a dynamic program over the pooled values: its state is the number of values placed in each group so far and the doubled rank sum of each group. Given the tie pattern, HH is an increasing function of ∑iRi2/ni\sum_i R_i^2 / n_i, so line L7 compares the integer ∑i(2Ri)2⋅L/ni\sum_i (2R_i)^2 \cdot L / n_i with L=lcm⁡(n1,…,nk)L = \operatorname{lcm}(n_1, \ldots, n_k), which is exact.

Example

Three groups. Take A=27,31,22,35A = 27, 31, 22, 35, B=19,24,20,18,26B = 19, 24, 20, 18, 26 and C=33,38,29,40C = 33, 38, 29, 40, so N=13N = 13. The pooled ranks are 7,9,4,117, 9, 4, 11 for AA, 2,5,3,1,62, 5, 3, 1, 6 for BB and 10,12,8,1310, 12, 8, 13 for CC. The rank sums are RA=31R_A = 31, RB=17R_B = 17 and RC=43R_C = 43, and they add up to 13⋅14/2=9113 \cdot 14 / 2 = 91. Line L3 gives

H=1213⋅14(3124+1725+4324)−42=3699455=8.130.H = \frac{12}{13 \cdot 14}\left(\frac{31^2}{4} + \frac{17^2}{5} + \frac{43^2}{4}\right) - 42 = \frac{3699}{455} = 8.130.

There are no ties, so C=1C = 1. The chi-square tail with 2 degrees of freedom gives p=0.0172p = 0.0172. The exact count over all 13!/(4! 5! 4!)=9009013!/(4!\,5!\,4!) = 90090 splits gives p=4/715=0.00559p = 4/715 = 0.00559, three times smaller. One-way ANOVA on the raw values gives F=9.72F = 9.72 and p=0.0045p = 0.0045.

Ties. For the groups 1,2,2,31, 2, 2, 3, then 2,3,4,42, 3, 4, 4, then 3,4,5,53, 4, 5, 5, the tie correction gives H=1727/273=6.326H = 1727/273 = 6.326. The chi-square p-value is 0.04230.0423 and the exact conditional p-value is 19/525=0.036219/525 = 0.0362.

Two groups. For x=1.1,3.4,2.9,5.0x = 1.1, 3.4, 2.9, 5.0 and y=0.8,2.0,1.9,2.9,1.2y = 0.8, 2.0, 1.9, 2.9, 1.2, the Kruskal-Wallis statistic is 1.83031.8303, which is the square of the Mann-Whitney z=1.3529z = 1.3529 without the continuity correction.

Correctness

The proof is in proofs/correctness.md. The two expressions for H′H' agree because ∑iRi=N(N+1)/2\sum_i R_i = N(N+1)/2. With midranks the total sum of squares of the ranks is (N3−N−∑j(tj3−tj))/12(N^3 - N - \sum_j (t_j^3 - t_j))/12, so dividing by CC gives H=(N−1)SSB/SSTH = (N - 1) SS_B / SS_T. Under H0H_0, exchangeability makes every split of the positions equally likely given the pooled values, so the exact p-value is a tail probability of a discrete law and is valid. The chi-square limit follows from the multivariate central limit theorem for the vector of mean ranks, whose covariance has rank k−1k - 1.

Proof: The Kruskal-Wallis statistic, its exact conditional p-value, and why both are validfull

We use the pseudocode of the page. The pooled sample has NN values with midranks r1,…,rNr_1, \ldots, r_N (line L1), group ii has size nin_i and rank sum RiR_i (line L2), and rˉ=(N+1)/2\bar r = (N+1)/2.

Claim 1 (the two forms of H′H'). 12N(N+1)∑ini(Rˉi−rˉ)2=12N(N+1)∑iRi2/ni−3(N+1)\frac{12}{N(N+1)} \sum_i n_i (\bar R_i - \bar r)^2 = \frac{12}{N(N+1)} \sum_i R_i^2/n_i - 3(N+1).

Proof. Midranks keep the total rank sum: ∑iRi=N(N+1)/2\sum_i R_i = N(N+1)/2, because replacing the ranks of a tie group by their mean does not change their sum. Expand: ∑ini(Rˉi−rˉ)2=∑iRi2/ni−2rˉ∑iRi+Nrˉ2=∑iRi2/ni−N(N+1)2/4\sum_i n_i (\bar R_i - \bar r)^2 = \sum_i R_i^2 / n_i - 2 \bar r \sum_i R_i + N \bar r^2 = \sum_i R_i^2/n_i - N(N+1)^2/4. Multiply by 12/(N(N+1))12/(N(N+1)). □\square

Claim 2 (the tie correction). With midranks, SST=∑l(rl−rˉ)2=N3−N12CSS_T = \sum_l (r_l - \bar r)^2 = \frac{N^3 - N}{12} C, so H=H′/C=(N−1)SSB/SSTH = H'/C = (N - 1) SS_B / SS_T with SSB=∑ini(Rˉi−rˉ)2SS_B = \sum_i n_i (\bar R_i - \bar r)^2, whenever C>0C > 0.

Proof. Without ties ∑l=1N(l−rˉ)2=(N3−N)/12\sum_{l=1}^{N} (l - \bar r)^2 = (N^3 - N)/12. A tie group covering ranks a+1,…,a+ta + 1, \ldots, a + t has mean m=a+(t+1)/2m = a + (t+1)/2. Replacing these ranks by mm keeps their sum and lowers ∑(r−rˉ)2\sum (r - \bar r)^2 by ∑s=1t(a+s−m)2=(t3−t)/12\sum_{s=1}^{t} (a + s - m)^2 = (t^3 - t)/12. So SST=(N3−N−∑j(tj3−tj))/12=N3−N12CSS_T = (N^3 - N - \sum_j (t_j^3 - t_j))/12 = \frac{N^3 - N}{12} C. Then H′/C=12 SSBN(N+1)⋅N3−N12 SST=(N−1)SSB/SSTH'/C = \frac{12\, SS_B}{N(N+1)} \cdot \frac{N^3 - N}{12\, SS_T} = (N - 1) SS_B / SS_T. If all values are tied, C=0C = 0 and the code returns H=0H = 0. □\square

Claim 3 (the null law). Under H0H_0, conditional on the multiset of pooled values, the assignment of the NN sorted positions to the groups is uniform over the N!/(n1!⋯nk!)N!/(n_1! \cdots n_k!) splits with the given sizes.

Proof. Under H0H_0 the NN observations are independent with one law, so their joint law is invariant under permutations of the observations. Given the multiset of values, every way of placing the observations in the sorted slots that is consistent with it is equally likely, so the set of slots of each group is a uniform split. The midranks depend only on the multiset. □\square

Claim 4 (the dynamic program). After line L6 has processed the first tt pooled values, the count stored for the state (sizes f1,…,fkf_1, \ldots, f_k, doubled rank sums s1,…,sks_1, \ldots, s_k) is the number of ways to assign these tt values to the groups so that group ii gets fif_i of them with doubled rank sum sis_i, and fi≤nif_i \le n_i.

Proof. Induction on tt. At t=0t = 0 only the empty assignment exists. Each assignment of the first tt values extends in one way for each group ii with fi<nif_i < n_i, adding 1 to fif_i and the doubled rank of value tt to sis_i; the code makes exactly these moves and adds the counts. At t=Nt = N every state has fi=nif_i = n_i, and the code sums the counts over the sizes to get the number of splits for each vector of rank sums. □\square

Claim 5 (the ordering). Given the tie pattern, HH is a strictly increasing function of Q=∑iRi2/niQ = \sum_i R_i^2 / n_i, and Q≥QobsQ \ge Q_{obs} exactly when the integer ∑i(2Ri)2L/ni\sum_i (2R_i)^2 L / n_i is at least its observed value, where L=lcm⁡(n1,…,nk)L = \operatorname{lcm}(n_1, \ldots, n_k).

Proof. By Claim 1, H=(12N(N+1)Q−3(N+1))/CH = (\frac{12}{N(N+1)} Q - 3(N+1))/C with C>0C > 0 fixed by the tie pattern. Multiplying QQ by the positive integer 4L4L keeps the order and makes every term an integer, because nin_i divides LL. □\square

Claim 6 (validity of the exact p-value). For every α\alpha, PH0(p≤α)≤αP_{H_0}(p \le \alpha) \le \alpha.

Proof. By Claims 3 to 5, line L8 returns P(Q≥Qobs)P(Q \ge Q_{obs}) under the uniform law of splits, given the pooled values. The set of values qq with P(Q≥q)≤αP(Q \ge q) \le \alpha is empty or has a least element q∗q^*, and the conditional probability of rejection is P(Q≥q∗)≤αP(Q \ge q^*) \le \alpha. Averaging over the pooled values keeps the bound. □\square

The chi-square limit (the asymptotic p-value). Under the uniform law of splits without ties, ERˉi=rˉE \bar R_i = \bar r, Var⁡Rˉi=(N−ni)(N+1)12ni\operatorname{Var} \bar R_i = \frac{(N - n_i)(N+1)}{12 n_i} and Cov⁡(Rˉi,Rˉj)=−N+112\operatorname{Cov}(\bar R_i, \bar R_j) = -\frac{N+1}{12} for i≠ji \ne j, from sampling without replacement. So the vector Zi=12ni/(N(N+1)) (Rˉi−rˉ)Z_i = \sqrt{12 n_i / (N(N+1))}\,(\bar R_i - \bar r) has covariance I−uu⊤I - u u^{\top} with ui=ni/Nu_i = \sqrt{n_i/N}, a projection of rank k−1k - 1, and H′=∑iZi2=∥Z∥2H' = \sum_i Z_i^2 = \lVert Z \rVert^2. When every ni→∞n_i \to \infty with ni/Nn_i/N bounded away from 0, the central limit theorem for linear rank statistics (Hájek's theorem for sampling without replacement) makes ZZ asymptotically normal with this covariance, and the squared length of such a vector is χk−12\chi^2_{k-1}. With ties the same argument applies to midranks with the variance multiplied by CC, which is why H=H′/CH = H'/C is used. The page's Monte Carlo runs show the size of the chi-square test approaching 0.050.05 as the groups grow. This part gives an approximation, not a bound, and the page says so.

Cost. Lines L1 to L4 cost one sort and O(N)O(N) further work. The exact branch keeps at most ∏i<k(ni+1)(2Nni+1)\prod_{i<k} (n_i + 1)(2N n_i + 1) states, because the last group's size and rank sum are fixed by the others, and each of the NN steps updates each state in at most kk ways. □\square

Complexity

Lines L1 to L4 sort once and then scan, so the asymptotic test costs Θ(Nlog⁡N)\Theta(N \log N) time and Θ(N)\Theta(N) space, plus a fixed number of steps for the chi-square tail. The exact count of line L6 is much more expensive. After the first tt values, the sizes placed so far sum to tt and the rank sums add up to a known total, so the last group is determined by the others, and the number of states is at most ∏i<k(ni+1)(2Nni+1)\prod_{i < k} (n_i + 1)(2 N n_i + 1). Each value updates each state in kk ways, so the time is O(kN∏i<k(ni+1)(2Nni+1))O(k N \prod_{i < k} (n_i + 1)(2N n_i + 1)), polynomial in NN for fixed kk. For the example with N=13N = 13 it took 0.030.03 s of CPU time.

Properties

  • Distribution-free. Given the tie pattern, the exact null law depends only on the group sizes.
  • Invariant. HH does not change under an increasing transformation of the data.
  • Two groups. For k=2k = 2, H=z2H = z^2, where zz is the standardized Mann-Whitney statistic with the tie-corrected variance and no continuity correction.
  • Chi-square accuracy. Monte Carlo runs with normal data and r=4000r = 4000 samples gave chi-square sizes at α=0.05\alpha = 0.05 of 0.01180.0118 for three groups of 3 (seed 31), 0.04250.0425 for three groups of 5 (seed 32) and 0.0480.048 for three groups of 10 (seed 33).
  • Robust power. With Cauchy errors and three groups of 10, the test kept power 0.1840.184 for a shift of 1 while ANOVA had 0.0500.050 (Monte Carlo, r=2000r = 2000, seed 42).

Variants and improvements

  • Exact and Monte Carlo p-values. For small groups use the exact count; when it is too large, sample random splits and report (1+#{H(b)≥H})/(1+B)(1 + \#\{H^{(b)} \ge H\})/(1 + B), a valid permutation test p-value.
  • Follow-up comparisons. A significant HH says that some groups differ, not which. Dunn's test compares mean ranks of pairs with the pooled variance; pairwise Mann-Whitney tests need a multiple-comparison correction such as Bonferroni. Tukey's method for means is Tukey HSD.
  • Ordered alternatives. When the groups have a natural order, the Jonckheere-Terpstra test, which adds Mann-Whitney counts over ordered pairs of groups, has more power against monotone trends.
  • Blocks. For a randomized block design, where observations are related within blocks, use the Friedman test.
  • The F approximation. Running ANOVA on the ranks gives an F statistic that is a monotone function of HH; its F p-value is another approximation to the same exact law.

When to use it

Use it to compare three or more independent groups when the data are ordinal, skewed or contain outliers, and the question is whether some group tends to give larger values. When the groups are close to normal with equal variances, ANOVA has slightly more power. For two groups use the Mann-Whitney test directly, which also has one-sided versions.

Pitfalls

  • The chi-square approximation at small sizes. For three groups of 3 the chi-square test had size 0.01180.0118 in the Monte Carlo run, and for the example with N=13N = 13 it gave p=0.0172p = 0.0172 against the exact 0.00560.0056. Use the exact count when the groups are small.
  • Not a test of medians. As for the Mann-Whitney test, groups with equal medians but different shapes can give large HH, and groups with different spreads but P(Xi>Xj)=1/2P(X_i > X_j) = 1/2 do not control the size.
  • Missing tie correction. Without dividing by CC the statistic is too small and the test conservative.
  • Related groups. Measurements on the same subjects under several conditions are not independent groups; use the Friedman test.

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.

kruskal_wallis_core.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kruskal-wallis-test/. The authors are listed in prov/DCECK4.jsonl.

import math
from fractions import Fraction

from stdist import chi2_sf


def doubled_midranks(values: list[float]) -> list[int]:
    """Return 2 x (midrank of each value), in input order. Doubling keeps midranks integers."""
    n = len(values)
    order = sorted(range(n), key=values.__getitem__)
    r2 = [0] * n
    i = 0
    while i < n:
        j = i
        while j + 1 < n and values[order[j + 1]] == values[order[i]]:
            j += 1
        for t in range(i, j + 1):
            r2[order[t]] = i + j + 2  # 2 x the mean of the ranks i + 1, ..., j + 1
        i = j + 1
    return r2


def tie_sizes(values: list[float]) -> list[int]:
    """Sizes of the groups of equal values."""
    counts: dict[float, int] = {}
    for v in values:
        counts[v] = counts.get(v, 0) + 1
    return list(counts.values())


def h_statistic(groups: list[list[float]]) -> Fraction:
    """The tie-corrected Kruskal-Wallis H as an exact Fraction (the inputs are compared only)."""
    sizes = [len(g) for g in groups]
    big_n = sum(sizes)
    pooled = [v for g in groups for v in g]
    r2 = doubled_midranks(pooled)  # @line L1
    sums, start = [], 0
    for size in sizes:  # @line L2
        sums.append(Fraction(sum(r2[start:start + size]), 2))
        start += size
    h = Fraction(12, big_n * (big_n + 1)) * sum(s * s / size for s, size in zip(sums, sizes))
    h -= 3 * (big_n + 1)  # @line L3
    c = 1 - Fraction(sum(t**3 - t for t in tie_sizes(pooled)), big_n**3 - big_n)  # @line L4
    return h / c if c > 0 else Fraction(0)


def labeling_counts(r2: list[int], sizes: list[int]) -> dict[tuple[int, ...], int]:
    """Number of ways to split the pooled doubled ranks into groups of the given sizes,
    by the vector of doubled rank sums of the groups. A DP over the pooled values whose
    state is (group sizes filled so far, rank sums so far)."""
    k = len(sizes)
    states: dict[tuple[tuple[int, ...], tuple[int, ...]], int] = {((0,) * k, (0,) * k): 1}
    for r in r2:
        nxt: dict[tuple[tuple[int, ...], tuple[int, ...]], int] = {}
        for (filled, sums), cnt in states.items():
            for i in range(k):
                if filled[i] < sizes[i]:
                    key = (filled[:i] + (filled[i] + 1,) + filled[i + 1:],
                           sums[:i] + (sums[i] + r,) + sums[i + 1:])
                    nxt[key] = nxt.get(key, 0) + cnt
        states = nxt
    out: dict[tuple[int, ...], int] = {}
    for (_, sums), cnt in states.items():
        out[sums] = out.get(sums, 0) + cnt
    return out


def kruskal_wallis(
    groups: list[list[float]], method: str = "asymptotic", exact: bool = False
) -> tuple[float, float | Fraction]:
    """Kruskal-Wallis test of H0: the k groups come from the same distribution.

    Returns (H, p). method "asymptotic" uses the upper tail of chi-square with
    k - 1 degrees of freedom. method "exact" counts every split of the pooled
    ranks into groups of the given sizes (the permutation null, exact and
    conditional on the ties); the p-value is the share of splits whose
    sum of R_i^2 / n_i is at least the observed one. exact=True returns a Fraction.
    """
    if len(groups) < 2 or any(len(g) == 0 for g in groups):
        raise ValueError("need at least two nonempty groups")
    if method not in ("asymptotic", "exact"):
        raise ValueError("unknown method")
    h = h_statistic(groups)
    k = len(groups)
    if method == "asymptotic":  # @line L5
        return float(h), chi2_sf(float(h), k - 1)
    sizes = [len(g) for g in groups]
    pooled = [v for g in groups for v in g]
    r2 = doubled_midranks(pooled)
    lcm = math.lcm(*sizes)

    def score(sums: tuple[int, ...]) -> int:
        # (4 lcm) x sum R_i^2 / n_i, an integer, increasing in H.
        return sum(s * s * (lcm // size) for s, size in zip(sums, sizes))

    observed, start = [], 0
    for size in sizes:
        observed.append(sum(r2[start:start + size]))
        start += size
    target = score(tuple(observed))
    counts = labeling_counts(r2, sizes)  # @line L6
    hits = sum(cnt for sums, cnt in counts.items() if score(sums) >= target)  # @line L7
    total = math.factorial(sum(sizes))
    for size in sizes:
        total //= math.factorial(size)
    p = Fraction(hits, total)
    return float(h), (p if exact else float(p))  # @line L8
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)
kruskal_wallis_test.py 10 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kruskal-wallis-test/. The authors are listed in prov/DCECK4.jsonl.
"""Entry point named after the slug. The code lives in kruskal_wallis_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""

from kruskal_wallis_core import (
    doubled_midranks, h_statistic, kruskal_wallis, labeling_counts, tie_sizes,
)

__all__ = ["doubled_midranks", "h_statistic", "kruskal_wallis", "labeling_counts", "tie_sizes"]
test_kruskal_wallis_test.py 139 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kruskal-wallis-test/. The authors are listed in prov/DCECK4.jsonl.

import itertools
import math
import random
from fractions import Fraction

import pytest

from kruskal_wallis_test import doubled_midranks, h_statistic, kruskal_wallis, labeling_counts

A = [27, 31, 22, 35]
B = [19, 24, 20, 18, 26]
C = [33, 38, 29, 40]


def h_direct(groups: list[list[float]]) -> Fraction:
    """H = (N - 1) SSB / SST on the midranks: a second formula, tie-corrected by itself."""
    pooled = [v for g in groups for v in g]
    big_n = len(pooled)
    ranks = []
    for v in pooled:
        ranks.append(sum(1 for t in pooled if t < v) + Fraction(sum(1 for t in pooled if t == v) + 1, 2))
    mean = Fraction(big_n + 1, 2)
    sst = sum((r - mean) ** 2 for r in ranks)
    ssb, start = Fraction(0), 0
    for g in groups:
        part = ranks[start:start + len(g)]
        ssb += len(g) * (sum(part) / len(g) - mean) ** 2
        start += len(g)
    return (big_n - 1) * ssb / sst if sst else Fraction(0)


def brute_force_p(groups: list[list[float]]) -> Fraction:
    """Share of all distinct assignments of the pooled values to the groups with H >= observed."""
    sizes = [len(g) for g in groups]
    pooled = [v for g in groups for v in g]
    h_obs = h_direct(groups)
    hits = total = 0
    for perm in itertools.permutations(range(len(pooled))):
        cut, start, ok = [], 0, True
        for size in sizes:
            block = perm[start:start + size]
            if list(block) != sorted(block):  # one representative per assignment of positions
                ok = False
                break
            cut.append([pooled[i] for i in block])
            start += size
        if not ok:
            continue
        total += 1
        hits += h_direct(cut) >= h_obs
    return Fraction(hits, total)


def test_page_example() -> None:
    assert h_statistic([A, B, C]) == Fraction(3699, 455)
    assert kruskal_wallis([A, B, C], "exact", exact=True)[1] == Fraction(4, 715)
    assert kruskal_wallis([A, B, C])[1] == pytest.approx(0.0171658, abs=1e-7)
    g2 = [[1, 2, 2, 3], [2, 3, 4, 4], [3, 4, 5, 5]]
    assert h_statistic(g2) == Fraction(1727, 273)
    assert kruskal_wallis(g2, "exact", exact=True)[1] == Fraction(19, 525)


def test_two_formulas_agree() -> None:
    rng = random.Random(1)
    for _ in range(200):
        k = rng.randint(2, 4)
        groups = [[rng.randint(0, 6) for _ in range(rng.randint(1, 5))] for _ in range(k)]
        if len(set(v for g in groups for v in g)) == 1:
            continue  # all values tied: H is 0 by convention
        assert h_statistic(groups) == h_direct(groups)


def test_two_groups_is_mann_whitney_squared() -> None:
    rng = random.Random(2)
    for _ in range(100):
        m, n = rng.randint(1, 7), rng.randint(1, 7)
        x = [rng.randint(0, 5) for _ in range(m)]
        y = [rng.randint(0, 5) for _ in range(n)]
        pooled = x + y
        big_n = m + n
        ties = sum(pooled.count(v) ** 3 - pooled.count(v) for v in set(pooled))
        var = Fraction(m * n, 12) * ((big_n + 1) - Fraction(ties, big_n * (big_n - 1)))
        if var == 0:
            continue
        r2 = doubled_midranks(pooled)
        u = Fraction(sum(r2[:m]), 2) - Fraction(m * (m + 1), 2)
        assert h_statistic([x, y]) == (u - Fraction(m * n, 2)) ** 2 / var


def test_exact_against_all_assignments() -> None:
    rng = random.Random(3)
    for _ in range(25):
        sizes = rng.choice([(2, 2, 2), (1, 2, 3), (3, 3), (2, 2, 3), (1, 1, 2, 2)])
        groups = [[rng.randint(0, 4) for _ in range(s)] for s in sizes]
        if len(set(v for g in groups for v in g)) == 1:
            continue
        assert kruskal_wallis(groups, "exact", exact=True)[1] == brute_force_p(groups)


def test_labeling_counts_total() -> None:
    r2 = doubled_midranks([1, 2, 2, 3, 5, 5, 7, 8, 9])
    counts = labeling_counts(r2, [2, 3, 4])
    assert sum(counts.values()) == math.factorial(9) // (2 * 6 * 24)
    assert all(sum(s) == sum(r2) for s in counts)


def test_exact_critical_value_333() -> None:
    # Sizes 3, 3, 3 without ties: P(H >= 5.6) = 0.05 exactly, and P(H >= 5.991) = 0.0107.
    r2 = [2 * i for i in range(1, 10)]
    counts = labeling_counts(r2, [3, 3, 3])
    total = sum(counts.values())

    def h(sums: tuple[int, ...]) -> Fraction:
        return Fraction(12, 90) * sum(Fraction(s, 2) ** 2 / 3 for s in sums) - 30

    assert total == 1680
    assert Fraction(sum(c for s, c in counts.items() if h(s) >= Fraction(28, 5)), total) == Fraction(1, 20)
    assert Fraction(sum(c for s, c in counts.items() if h(s) >= Fraction(5991, 1000)), total) == Fraction(18, 1680)


def test_chi_square_size_monte_carlo() -> None:
    rng = random.Random(33)
    r, alpha = 1500, 0.05
    hits = sum(kruskal_wallis([[rng.gauss(0.0, 1.0) for _ in range(10)] for _ in range(3)])[1] <= alpha
               for _ in range(r))
    assert abs(hits / r - alpha) <= 4 * math.sqrt(alpha * (1 - alpha) / r)


def test_edges() -> None:
    with pytest.raises(ValueError):
        kruskal_wallis([[1.0]])
    with pytest.raises(ValueError):
        kruskal_wallis([[1.0], []])
    with pytest.raises(ValueError):
        kruskal_wallis([[1.0], [2.0]], method="other")
    assert h_statistic([[1.0, 1.0], [1.0]]) == 0

History

William Kruskal and W. Allen Wallis published the test in 1952 as an extension of the Wilcoxon and Mann-Whitney two-sample test, with the chi-square approximation, the tie correction, tables of the exact distribution for three small groups, and a survey of earlier work on rank tests. The efficiency results of Hodges and Lehmann (1956) for the Wilcoxon test carry over to it.

References

  1. Myles Hollander, Douglas A. Wolfe and Eric Chicken, Nonparametric Statistical Methods, third edition, Wiley, 2014, Chapter 6 (the one-way layout), the section on the Kruskal-Wallis test
  2. E. L. Lehmann, Nonparametrics, Statistical Methods Based on Ranks, revised edition, Springer, 2006, The chapter on the comparison of more than two treatments (the Kruskal-Wallis test and its limit law)
  3. William H. Kruskal and W. Allen Wallis, Use of ranks in one-criterion variance analysis, Journal of the American Statistical Association 47(260), 1952, pp. 583 to 621 (the statistic H, the chi-square approximation, the tie correction and tables for three groups)

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.

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