Algorithm Search⌘K

Algorithmcore

Mann-Whitney U test

Also called Wilcoxon rank-sum test, Mann-Whitney-Wilcoxon test.

Compares two independent samples by the number of pairs in which the first sample's value exceeds the second's, equivalently the rank sum of one sample.

Time
Θ(m^2 n^2) worst · best
Space
Θ(m n min(m, n)) extra
Where
m = the size of the first sample; n = the size of the second sample
Properties
deterministicexactofflineiterative
Origin
Frank Wilcoxon, Henry B. Mann, Donald R. Whitney, 1945

The Mann-Whitney U test compares two independent samples x1,…,xmx_1, \ldots, x_m and y1,…,yny_1, \ldots, y_n. Its statistic UU counts the pairs (xi,yj)(x_i, y_j) with xi>yjx_i > y_j, with ties counted as one half. Equivalently, rank the pooled sample and add the ranks of the xx values: this rank sum WW is Wilcoxon's statistic, and U=W−m(m+1)/2U = W - m(m+1)/2. Under the null hypothesis that both samples come from the same distribution, every choice of which mm of the pooled values form the first sample is equally likely, so UU has an exact law that a dynamic program counts. U/(mn)U/(mn) estimates P(X>Y)+12P(X=Y)P(X > Y) + \frac{1}{2} P(X = Y), the area under the ROC curve, and the test is consistent exactly against alternatives where this value differs from 1/21/2.

In plain words

Two groups of plants get two fertilizers. Take every plant from the first group and every plant from the second, and count how many times the first-group plant is the taller one. A tie counts as half a win.

If the fertilizers act the same, the first group should win about half of the pairs. Winning almost all of them is unlikely by luck. To judge how unlikely, imagine the group labels shuffled at random among all plants, and count how often a shuffle gives this many wins or more. Only the order of the heights matters, so one very tall plant counts no more than a slightly tall one.

The problem

Model. X1,…,XmX_1, \ldots, X_m are independent with distribution FF, and Y1,…,YnY_1, \ldots, Y_n are independent with distribution GG, independent of the XX values.

Hypotheses. H0H_0: F=GF = G. The alternatives are about θ=P(X>Y)+12P(X=Y)\theta = P(X > Y) + \frac{1}{2} P(X = Y): "greater" is θ>1/2\theta > 1/2 (the XX values tend to be larger), "less" is θ<1/2\theta < 1/2, and two-sided is θ≠1/2\theta \ne 1/2. In the shift model G(t)=F(t−Δ)G(t) = F(t - \Delta) these are Δ<0\Delta < 0, Δ>0\Delta > 0 and Δ≠0\Delta \ne 0.

Statistic. U=#{(i,j):xi>yj}+12#{(i,j):xi=yj}U = \#\{(i, j) : x_i > y_j\} + \frac{1}{2} \#\{(i, j) : x_i = y_j\}. With midranks RiR_i of the xx values in the pooled sample, U=∑i=1mRi−m(m+1)/2U = \sum_{i=1}^m R_i - m(m+1)/2.

Null distribution. Exact and conditional on the pooled values. Under H0H_0 the N=m+nN = m + n values are exchangeable, so given the multiset of pooled values, each of the (Nm)\binom{N}{m} ways to choose the positions of the first sample has probability 1/(Nm)1/\binom{N}{m}. The mean of UU is mn/2mn/2 and the variance is mn12[(N+1)−∑j(tj3−tj)N(N−1)]\frac{mn}{12}\left[(N + 1) - \frac{\sum_j (t_j^3 - t_j)}{N(N-1)}\right], with tjt_j the sizes of the tie groups. Without ties the law is symmetric about mn/2mn/2; with ties it can be asymmetric.

P-values. With c(u)c(u) the number of choices that give U=uU = u and C=(Nm)C = \binom{N}{m}:

  • Greater: Phi(u)=∑v≥uc(v)/CP_{hi}(u) = \sum_{v \ge u} c(v) / C.
  • Less: Plo(u)=∑v≤uc(v)/CP_{lo}(u) = \sum_{v \le u} c(v) / C.
  • Two-sided: p(u)=min⁡{1,2min⁡(Plo(u),Phi(u))}p(u) = \min\{1, 2 \min(P_{lo}(u), P_{hi}(u))\}. Without ties this equals P(∣U−mn/2∣≥∣u−mn/2∣)P(\lvert U - mn/2 \rvert \ge \lvert u - mn/2 \rvert).

Rejection rule and size. Reject at level α\alpha when p(u)≤αp(u) \le \alpha. The size is at most α\alpha for every mm and nn, conditionally on the tie pattern and therefore also overall.

Sensitivity and power. U/(mn)U/(mn) converges to θ\theta, so the test is consistent against every alternative with θ≠1/2\theta \ne 1/2 and against no alternative with θ=1/2\theta = 1/2. When θ=1/2\theta = 1/2 but F≠GF \ne G, the rejection rate can be far from α\alpha in either direction (see Properties). In the shift model its asymptotic efficiency against the two-sample t-test is 3/π≈0.9553/\pi \approx 0.955 for normal data and at least 0.8640.864 for every continuous law (Hodges and Lehmann 1956), the same values as for the signed-rank test.

The algorithm

  1. MANN-WHITNEY(x_1, ..., x_m, y_1, ..., y_n, alternative)
  2. 1r ← 2 · (midranks of the pooled values x_1, ..., x_m, y_1, ..., y_n) ▷ integers
  3. 2u ← (r_1 + ... + r_m) - m(m + 1) ▷ u = 2U
  4. 3k ← min(m, n); c[j][s] ← 0 for all j, s; c[0][0] ← 1
  5. 4for each pooled value i
  6. 5for j ← k down to 1, for s ← top down to r_i: c[j][s] ← c[j][s] + c[j - 1][s - r_i]
  7. 6map each s with c[k][s] > 0 to 2U: s - m(m + 1) if k = m, else 2mn - (s - n(n + 1))
  8. 7A ← number of choices with 2U ≥ u; B ← number with 2U ≤ u
  9. 8return A / C(N, m), B / C(N, m) or min(1, 2 · min(A, B) / C(N, m)) for greater, less or two-sided

Here toptop is the largest sum of kk doubled ranks. After line L5 has processed all NN values, c[j][s]c[j][s] is the number of jj-element sets of positions whose doubled ranks add up to ss. This is the count of subsets by their sum with one more index for the size. Counting subsets of the smaller size kk keeps the table small; if k=nk = n the counted set is the second sample, and line L6 converts its rank sum to UU of the first sample through Ux+Uy=mnU_x + U_y = mn. Doubled midranks keep every index an integer, so the counts are exact even with ties. The code returns UU and the p-value, and also offers the normal approximation with the tie-corrected variance and a continuity correction of 1/21/2.

Example

Two small samples. Take 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, so m=4m = 4, n=5n = 5. In the pooled order 0.8,1.1,1.2,1.9,2.0,2.9,2.9,3.4,5.00.8, 1.1, 1.2, 1.9, 2.0, 2.9, 2.9, 3.4, 5.0 the xx values have ranks 22, 6.56.5, 88 and 99; the two values 2.92.9 share the midrank 6.56.5. So W=25.5W = 25.5 and U=25.5−10=15.5U = 25.5 - 10 = 15.5 out of mn=20mn = 20. Counting pairs gives the same: 1.11.1 beats one yy, 3.43.4 and 5.05.0 beat all five, and 2.92.9 beats four and ties one. Lines L3 to L7 over the (94)=126\binom{9}{4} = 126 choices give 1313 with U≥15.5U \ge 15.5, so the one-sided p-value is 13/126=0.10313/126 = 0.103 and the two-sided p-value is 13/63=0.20613/63 = 0.206. The normal approximation gives z=1.230z = 1.230 and p=0.219p = 0.219 with the continuity correction, and z=1.353z = 1.353 and p=0.176p = 0.176 without it. The estimate of P(X>Y)P(X > Y) is 15.5/20=0.77515.5/20 = 0.775.

A null law. For m=2m = 2, n=3n = 3 without ties, the 10 choices give U=0,1,2,3,4,5,6U = 0, 1, 2, 3, 4, 5, 6 with counts 1,1,2,2,2,1,11, 1, 2, 2, 2, 1, 1, symmetric about mn/2=3mn/2 = 3.

Ties break the symmetry. For pooled ranks 1,2.5,2.5,4,51, 2.5, 2.5, 4, 5 and m=2m = 2, the 10 choices give U=0.5,2,3,3.5,4.5,6U = 0.5, 2, 3, 3.5, 4.5, 6 with counts 2,2,1,2,2,12, 2, 1, 2, 2, 1. The mean is still 33, but the law is not symmetric about it, so with ties the doubled tail is a valid p-value but not the same as the rule based on ∣U−mn/2∣\lvert U - mn/2 \rvert.

Correctness

The proof is in proofs/correctness.md. Under H0H_0 the pooled sample is exchangeable, so given the multiset of values all (Nm)\binom{N}{m} position sets for the first sample are equally likely. UU depends on the position set only through the sum of its ranks. After all values pass line L5, c[j][s]c[j][s] counts the jj-sets with doubled rank sum ss, by the same include-or-exclude induction as for subset sums. Line L6 maps each sum to 2U2U, lines L7 and L8 give the exact tails, and each p-value is valid by the usual argument for tail probabilities of a discrete law.

Proof: The Mann-Whitney test computes the exact conditional null law of U, and each p-value is validfull

We use the pseudocode of the page. Write N=m+nN = m + n, let v1,…,vNv_1, \ldots, v_N be the pooled values with the xx values first, and let r1,…,rNr_1, \ldots, r_N be their doubled midranks (line L1).

Claim 1 (U from ranks). 2U=∑i=1mri−m(m+1)2U = \sum_{i=1}^m r_i - m(m+1), as line L2 computes.

Proof. The midrank of xix_i is 1+#{pooled values<xi}+12(#{pooled values=xi}−1)1 + \#\{\text{pooled values} < x_i\} + \frac{1}{2}(\#\{\text{pooled values} = x_i\} - 1). Sum over ii and split the pooled values into xx values and yy values. The xx part gives ∑i[#{xl<xi}+12#{l≠i:xl=xi}]=(m2)\sum_i [\#\{x_l < x_i\} + \frac{1}{2}\#\{l \ne i : x_l = x_i\}] = \binom{m}{2}, because each unordered pair of xx values contributes exactly 1 (either one is smaller, or both get 12\frac{1}{2}). The yy part gives ∑i,j[1{yj<xi}+121{yj=xi}]=U\sum_{i, j} [\mathbf{1}\{y_j < x_i\} + \frac{1}{2}\mathbf{1}\{y_j = x_i\}] = U. So ∑iRi=m+(m2)+U=m(m+1)/2+U\sum_i R_i = m + \binom{m}{2} + U = m(m+1)/2 + U. □\square

Claim 2 (the null law). Under H0H_0, conditional on the multiset of pooled values, the set SS of positions (in the sorted pooled order) taken by the xx values is uniform over the (Nm)\binom{N}{m} subsets of size mm, and 2U=∑i∈Sri−m(m+1)2U = \sum_{i \in S} r_i - m(m + 1).

Proof. Under H0H_0 the NN variables are independent with the same law, so their joint law is invariant under permutations: the vector is exchangeable. Given the multiset of values, every assignment of the values to the NN slots that is consistent with it has the same conditional probability, so the set of slots holding the first mm variables is uniform. Midranks are functions of the multiset, so Claim 1 gives the formula. □\square

Claim 3 (the table). After line L5 has processed the values 1,…,i1, \ldots, i, c[j][s]c[j][s] is the number of jj-element sets J⊆{1,…,i}J \subseteq \{1, \ldots, i\} with ∑l∈Jrl=s\sum_{l \in J} r_l = s, for 0≤j≤k0 \le j \le k and 0≤s≤top0 \le s \le top.

Proof. Induction on ii. At the start only the empty set exists, so c[0][0]=1c[0][0] = 1 and every other entry is 0. A jj-set inside {1,…,i}\{1, \ldots, i\} either leaves out ii (counted by the old c[j][s]c[j][s]) or is J′∪{i}J' \cup \{i\} for a (j−1)(j-1)-set J′J' with sum s−ris - r_i (counted by the old c[j−1][s−ri]c[j - 1][s - r_i]). Line L5 runs jj downward, so c[j−1]c[j - 1] is still the old row when c[j]c[j] is updated; row 00 never changes, which is correct because only the empty set has size 0. Every sum of kk doubled ranks is at most toptop, so no count is lost. □\square

Claim 4 (the conversion). Line L6 gives the number c(u)c(u) of size-mm sets SS with 2U=u2U = u.

Proof. If k=mk = m, apply Claim 2 directly to c[m][s]c[m][s]. If k=n<mk = n < m, the complement T={1,…,N}∖ST = \{1, \ldots, N\} \setminus S is an nn-set, and S↦TS \mapsto T is a bijection. The pairs (xi,yj)(x_i, y_j) split into x>yx > y, x<yx < y and x=yx = y, so Ux+Uy=mnU_x + U_y = mn, and Claim 1 for the yy sample gives 2Uy=∑l∈Trl−n(n+1)2U_y = \sum_{l \in T} r_l - n(n+1). So 2Ux=2mn−(s−n(n+1))2U_x = 2mn - (s - n(n+1)) with s=∑l∈Trls = \sum_{l \in T} r_l. □\square

Claim 5 (validity). Lines L7 and L8 return PhiP_{hi}, PloP_{lo} and the doubled smaller tail of the conditional null law, and for every α\alpha, PH0(p≤α)≤αP_{H_0}(p \le \alpha) \le \alpha.

Proof. By Claims 2 to 4, A/(Nm)A / \binom{N}{m} and B/(Nm)B / \binom{N}{m} are the exact conditional tails. For a one-sided p-value, the rejection set {u:P(2U≥u)≤α}\{u : P(2U \ge u) \le \alpha\} is empty or an upper set with least element u∗u^*, and its conditional probability is P(2U≥u∗)≤αP(2U \ge u^*) \le \alpha; the lower tail is the same. For the two-sided p-value, p≤αp \le \alpha forces one tail to be at most α/2\alpha/2, and each such event has conditional probability at most α/2\alpha/2. This needs no symmetry, so it holds with ties. Averaging over the multiset of pooled values gives the unconditional bound. □\square

Claim 6 (symmetry without ties). If the values are distinct, c(u)=c(2mn−u)c(u) = c(2mn - u).

Proof. Without ties rl=2lr_l = 2l. The map S↦{N+1−l:l∈S}S \mapsto \{N + 1 - l : l \in S\} is a bijection on mm-sets and sends the doubled rank sum ss to 2m(N+1)−s2m(N + 1) - s, hence 2U=s−m(m+1)2U = s - m(m+1) to 2m(N+1)−s−m(m+1)=2mn−2U2m(N+1) - s - m(m+1) = 2mn - 2U. □\square

With ties the reflection changes the tie pattern, and the law can be asymmetric; the tests give an example with ranks 1,2.5,2.5,4,51, 2.5, 2.5, 4, 5.

Moments. Under the uniform law of SS, E∑i∈SRi=m(N+1)/2E \sum_{i \in S} R_i = m (N+1)/2, so EU=mn/2E U = mn/2. Sampling mm of NN values without replacement, Var⁡∑i∈SRi=mnN(N−1)∑l(Rl−Rˉ)2\operatorname{Var} \sum_{i \in S} R_i = \frac{m n}{N(N - 1)} \sum_{l} (R_l - \bar R)^2. Without ties ∑l(Rl−Rˉ)2=(N3−N)/12\sum_l (R_l - \bar R)^2 = (N^3 - N)/12, and a tie group of size tt lowers it by (t3−t)/12(t^3 - t)/12. This gives the variance on the page; the tests check it in exact fractions.

Cost. With k=min⁡(m,n)k = \min(m, n), top=k(2N−k+1)top = k(2N - k + 1). Line L5 does at most toptop additions for each pair (i,j)(i, j) with 1≤i≤N1 \le i \le N and 1≤j≤k1 \le j \le k, so O(Nk⋅kN)=O(m2n2)O(N k \cdot kN) = O(m^2 n^2), because kN≤2mnk N \le 2 m n. For distinct values the inner range has length top−ri+1≥top−2N+1top - r_i + 1 \ge top - 2N + 1, which is Θ(kN)\Theta(kN) when k≥2k \ge 2, so the bound is tight. The table has (k+1)(top+1)=Θ(mnmin⁡(m,n))(k+1)(top+1) = \Theta(m n \min(m, n)) entries. □\square

Complexity

Line L1 sorts in O(Nlog⁡N)O(N \log N) with N=m+nN = m + n. Let k=min⁡(m,n)k = \min(m, n). The largest doubled rank sum of kk values is top=k(2N−k+1)=Θ(kN)top = k(2N - k + 1) = \Theta(kN), so the table has (k+1)(top+1)=Θ(k2N)(k + 1)(top + 1) = \Theta(k^2 N) entries, which is Θ(mnmin⁡(m,n))\Theta(m n \min(m, n)). Line L5 does Θ(top)\Theta(top) additions for each of the kk values of jj and each of the NN values of ii, so the time is Θ(N2k2)=Θ(m2n2)\Theta(N^2 k^2) = \Theta(m^2 n^2) additions. For m=n=30m = n = 30 the exact p-value took 0.210.21 s of CPU time in the Python code. The classic recursion of Mann and Whitney on the counts by UU has the same order. For large samples the normal approximation costs O(Nlog⁡N)O(N \log N).

Properties

  • Distribution-free. Under H0H_0 the conditional law depends only on mm, nn and the tie pattern.
  • Invariant. UU does not change under any increasing transformation applied to both samples.
  • Connection to AUC. U/(mn)U/(mn) is the empirical area under the ROC curve of a score that separates the two samples, and UU is a two-sample U-statistic with kernel 1{x>y}+121{x=y}\mathbf{1}\{x > y\} + \frac{1}{2}\mathbf{1}\{x = y\}.
  • Not a test of medians. With X=E−ln⁡2X = E - \ln 2 and Y=ln⁡2−E′Y = \ln 2 - E', EE and E′E' exponential with mean 1, both medians are 0 but θ=14(1+2ln⁡2)=0.5966\theta = \frac{1}{4}(1 + 2 \ln 2) = 0.5966. A Monte Carlo run with m=n=50m = n = 50, r=1000r = 1000 samples and seed 21 rejected at α=0.05\alpha = 0.05 in 41.2%41.2\% of samples, with the normal approximation.
  • Unequal spreads. With F=N(0,1)F = N(0, 1), G=N(0,16)G = N(0, 16), θ=1/2\theta = 1/2 but F≠GF \ne G. With m=10m = 10, n=40n = 40, r=2000r = 2000 samples and seed 22, the test rejected in 0.9%0.9\% of samples at the nominal 5%5\%. With the spreads exchanged (m=10m = 10 with standard deviation 4, n=40n = 40 with standard deviation 1) and seed 23 it rejected in 14.25%14.25\%. The test does not control the size for this problem.

Variants and improvements

  • Rank-sum form. Wilcoxon's W=U+m(m+1)/2W = U + m(m + 1)/2 gives the same p-values.
  • Normal approximation. z=(U−mn/2∓1/2)/σz = (U - mn/2 \mp 1/2)/\sigma with the tie-corrected σ\sigma above. For the example it gave 0.2190.219 against the exact 0.2060.206.
  • Estimator and interval. The Hodges-Lehmann estimator of the shift is the median of the mnmn differences yj−xiy_j - x_i, and inverting the test gives an interval between two order statistics of these differences.
  • Unequal spreads. The Brunner-Munzel test estimates the variance of UU under θ=1/2\theta = 1/2 without assuming F=GF = G, and so keeps the size approximately when the spreads differ.
  • Several samples. The Kruskal-Wallis test extends the rank sum to kk groups; for k=2k = 2 its statistic is the square of the zz of this test without the continuity correction.
  • Other two-sample tests. The two-sample Kolmogorov-Smirnov test reacts to any difference between FF and GG, including a difference in spread, at the cost of power against shifts. A permutation test on the difference of means uses the same exchangeability with the raw values.

When to use it

Use it to compare two independent groups when the data are ordinal or skewed, or have outliers, and the question is whether one group tends to give larger values. It is a good default in place of the Welch t-test when normality is in doubt, but only if the two distributions have similar shapes or the question is really about P(X>Y)P(X > Y). For paired data use the signed-rank test.

Pitfalls

  • It is not a test of medians or means. Equal medians gave a 41.2%41.2\% rejection rate in the Monte Carlo run above.
  • Unequal spreads. With F≠GF \ne G but θ=1/2\theta = 1/2, the size was 0.9%0.9\% or 14.25%14.25\% at the nominal 5%5\%, depending on which sample is the smaller one.
  • Conventions for UU. Some books and programs report #{xi<yj}\#\{x_i < y_j\}, which is mn−Umn - U, or the smaller of the two, or the rank sum WW. Check which one before using a table.
  • Ties and the normal approximation. Without the tie correction the variance is too large and the test conservative. The exact count handles ties.
  • Paired data. Applying the rank-sum test to paired data ignores the pairing and loses 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.

mann_whitney_core.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mann-whitney-u-test/. The authors are listed in prov/9WF4CP.jsonl.

import math
from fractions import Fraction

ALTERNATIVES = ("two-sided", "greater", "less")


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 u_statistic(x: list[float], y: list[float]) -> float:
    """U = #{(i, j) : x_i > y_j} + #{(i, j) : x_i = y_j} / 2, from the rank sum of x."""
    m = len(x)
    r2 = doubled_midranks(list(x) + list(y))
    return (sum(r2[:m]) - m * (m + 1)) / 2


def null_counts_2u(r2: list[int], m: int) -> dict[int, int]:
    """Number of ways to pick the m positions of the first sample, by the value of 2U.

    A subset-sum count over the pooled doubled ranks r2, restricted to subsets of
    size k = min(m, n). If k = n the subset is the second sample, and 2U of the
    first sample is 2mn minus 2U of the second.
    """
    big_n = len(r2)
    n = big_n - m
    k = min(m, n)
    top = sum(sorted(r2)[big_n - k:])  # the largest possible doubled rank sum of k values
    c = [[0] * (top + 1) for _ in range(k + 1)]  # @line L3
    c[0][0] = 1
    for r in r2:  # @line L4
        for j in range(k, 0, -1):  # @line L5
            row, prev = c[j], c[j - 1]
            for s in range(top, r - 1, -1):
                if prev[s - r]:
                    row[s] += prev[s - r]
    out: dict[int, int] = {}
    for s, cnt in enumerate(c[k]):  # @line L6
        if cnt:
            u2 = s - m * (m + 1) if k == m else 2 * m * n - (s - n * (n + 1))
            out[u2] = out.get(u2, 0) + cnt
    return out


def mann_whitney(
    x: list[float], y: list[float], alternative: str = "two-sided", exact: bool = False
) -> tuple[float, float | Fraction]:
    """Mann-Whitney U test of H0: the two samples come from the same distribution.

    Returns (U, p) with U = #{x_i > y_j} + (1/2) #{x_i = y_j}. "greater" is the
    alternative that X tends to be larger than Y. Ties get midranks, and the
    p-value is then exact for the conditional null law given the tie pattern.
    The two-sided p-value doubles the smaller tail. Without ties the null law is
    symmetric about mn/2, and this equals P(|U - mn/2| >= |u - mn/2|); with ties
    the conditional law can be asymmetric, and doubling is still a valid rule.
    """
    if alternative not in ALTERNATIVES:
        raise ValueError("unknown alternative")
    m, n = len(x), len(y)
    if m == 0 or n == 0:
        raise ValueError("both samples must be nonempty")
    r2 = doubled_midranks(list(x) + list(y))  # @line L1
    u2 = sum(r2[:m]) - m * (m + 1)  # @line L2
    counts = null_counts_2u(r2, m)
    upper = sum(c for v, c in counts.items() if v >= u2)  # @line L7
    lower = sum(c for v, c in counts.items() if v <= u2)
    total = math.comb(m + n, m)
    if alternative == "greater":  # @line L8
        p = Fraction(upper, total)
    elif alternative == "less":
        p = Fraction(lower, total)
    else:
        p = min(Fraction(1), Fraction(2 * min(upper, lower), total))
    return u2 / 2, (p if exact else float(p))


def mann_whitney_normal(
    x: list[float], y: list[float], alternative: str = "two-sided", correction: bool = True
) -> tuple[float, float]:
    """Normal approximation with the tie-corrected variance. Returns (z, p)."""
    if alternative not in ALTERNATIVES:
        raise ValueError("unknown alternative")
    m, n = len(x), len(y)
    big_n = m + n
    u = u_statistic(x, y)
    mean = m * n / 2
    ties = sum(t**3 - t for t in tie_sizes(list(x) + list(y)))
    var = m * n / 12 * ((big_n + 1) - ties / (big_n * (big_n - 1)))
    sd = math.sqrt(var)
    c = 0.5 if correction else 0.0
    if alternative == "greater":
        z = (u - mean - c) / sd
        return z, 0.5 * math.erfc(z / math.sqrt(2.0))
    if alternative == "less":
        z = (u - mean + c) / sd
        return z, 0.5 * math.erfc(-z / math.sqrt(2.0))
    z = math.copysign(max(0.0, abs(u - mean) - c), u - mean) / sd
    return z, min(1.0, math.erfc(abs(z) / math.sqrt(2.0)))
mann_whitney_u_test.py 12 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mann-whitney-u-test/. The authors are listed in prov/9WF4CP.jsonl.
"""Entry point named after the slug. The code lives in mann_whitney_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""

from mann_whitney_core import (
    ALTERNATIVES, doubled_midranks, mann_whitney, mann_whitney_normal, null_counts_2u, tie_sizes,
    u_statistic,
)

__all__ = ["ALTERNATIVES", "doubled_midranks", "mann_whitney", "mann_whitney_normal",
           "null_counts_2u", "tie_sizes", "u_statistic"]
test_mann_whitney_u_test.py 138 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mann-whitney-u-test/. The authors are listed in prov/9WF4CP.jsonl.

import itertools
import math
import random
from fractions import Fraction

import pytest

from mann_whitney_u_test import (
    doubled_midranks, mann_whitney, mann_whitney_normal, null_counts_2u, tie_sizes, u_statistic,
)

X = [1.1, 3.4, 2.9, 5.0]
Y = [0.8, 2.0, 1.9, 2.9, 1.2]


def pair_count(x: list[float], y: list[float]) -> Fraction:
    return sum((Fraction(1) if a > b else Fraction(1, 2) if a == b else Fraction(0))
               for a in x for b in y)


def brute_force(x: list[float], y: list[float]) -> tuple[Fraction, Fraction, Fraction]:
    """U and its tails by listing every choice of m of the pooled values as the first sample."""
    pooled = list(x) + list(y)
    m, big_n = len(x), len(pooled)
    u = pair_count(x, y)
    upper = lower = total = 0
    for idx in itertools.combinations(range(big_n), m):
        chosen = set(idx)
        a = [pooled[i] for i in idx]
        b = [pooled[i] for i in range(big_n) if i not in chosen]
        v = pair_count(a, b)
        total += 1
        upper += v >= u
        lower += v <= u
    return u, Fraction(upper, total), Fraction(lower, total)


def test_page_examples() -> None:
    assert u_statistic(X, Y) == 15.5
    assert mann_whitney(X, Y, exact=True) == (15.5, Fraction(13, 63))
    assert mann_whitney(X, Y, "greater", exact=True) == (15.5, Fraction(13, 126))
    z, p = mann_whitney_normal(X, Y)
    assert (round(z, 4), round(p, 5)) == (1.2299, 0.21874)
    z, p = mann_whitney_normal(X, Y, correction=False)
    assert (round(z, 4), round(p, 5)) == (1.3529, 0.17610)
    assert sorted(null_counts_2u([2, 4, 6, 8, 10], 2).items()) == [
        (0, 1), (2, 1), (4, 2), (6, 2), (8, 2), (10, 1), (12, 1)]


def test_u_is_the_pair_count() -> None:
    rng = random.Random(1)
    for _ in range(300):
        x = [rng.randint(0, 5) for _ in range(rng.randint(1, 8))]
        y = [rng.randint(0, 5) for _ in range(rng.randint(1, 8))]
        assert Fraction(u_statistic(x, y)) == pair_count(x, y)
        assert u_statistic(x, y) + u_statistic(y, x) == len(x) * len(y)


def test_against_all_labelings() -> None:
    rng = random.Random(2)
    for _ in range(120):
        m, n = rng.randint(1, 6), rng.randint(1, 6)
        x = [rng.randint(0, 4) for _ in range(m)]  # small range: many ties
        y = [rng.randint(0, 4) for _ in range(n)]
        u, upper, lower = brute_force(x, y)
        assert mann_whitney(x, y, "greater", exact=True) == (float(u), upper)
        assert mann_whitney(x, y, "less", exact=True)[1] == lower
        assert mann_whitney(x, y, exact=True)[1] == min(Fraction(1), 2 * min(upper, lower))


def test_counts_both_orientations() -> None:
    # The table counts subsets of size min(m, n); both choices must give the same law of 2U.
    rng = random.Random(4)
    for _ in range(40):
        m, n = rng.randint(1, 7), rng.randint(1, 7)
        values = [rng.randint(0, 6) for _ in range(m + n)]
        r2 = doubled_midranks(values)
        a = null_counts_2u(r2, m)
        b = null_counts_2u(r2, n)  # the law of 2U for the other sample, mirrored about mn
        assert sum(a.values()) == math.comb(m + n, m)
        assert a == {2 * m * n - v: c for v, c in b.items()}
        distinct = null_counts_2u(list(range(2, 2 * (m + n) + 1, 2)), m)
        assert distinct == {2 * m * n - v: c for v, c in distinct.items()}  # symmetric, no ties


def test_ties_can_break_symmetry() -> None:
    # Ranks 1, 2.5, 2.5, 4, 5 with m = 2: the conditional law of U is not symmetric about mn/2.
    a = null_counts_2u(doubled_midranks([1, 2, 2, 3, 4]), 2)
    assert a != {12 - v: c for v, c in a.items()}


def test_null_mean_and_variance() -> None:
    for values, m in (([1, 2, 3, 4, 5, 6, 7, 8, 9], 4), ([1, 1, 2, 3, 3, 3, 4, 5, 5, 6], 4)):
        big_n = len(values)
        n = big_n - m
        counts = null_counts_2u(doubled_midranks(values), m)
        total = math.comb(big_n, m)
        mean = sum(Fraction(v, 2) * c for v, c in counts.items()) / total
        var = sum(Fraction(v, 2) ** 2 * c for v, c in counts.items()) / total - mean**2
        ties = sum(t**3 - t for t in tie_sizes(values))
        assert mean == Fraction(m * n, 2)
        assert var == Fraction(m * n, 12) * ((big_n + 1) - Fraction(ties, big_n * (big_n - 1)))


def test_size_monte_carlo() -> None:
    rng = random.Random(6)
    m, n, r, alpha = 8, 10, 1500, 0.05
    hits = 0
    for _ in range(r):
        x = [rng.gauss(0.0, 1.0) for _ in range(m)]
        y = [rng.gauss(0.0, 1.0) for _ in range(n)]
        hits += mann_whitney(x, y)[1] <= alpha
    assert hits / r <= alpha + 4 * math.sqrt(alpha * (1 - alpha) / r)


def test_equal_medians_are_not_enough() -> None:
    # X = E - ln 2 and Y = -(E - ln 2) both have median 0, but P(X > Y) = 0.597.
    rng = random.Random(21)
    m = n = 50
    r, alpha = 300, 0.05
    hits = 0
    for _ in range(r):
        x = [rng.expovariate(1.0) - math.log(2.0) for _ in range(m)]
        y = [math.log(2.0) - rng.expovariate(1.0) for _ in range(n)]
        hits += mann_whitney_normal(x, y)[1] <= alpha
    assert hits / r > alpha + 4 * math.sqrt(alpha * (1 - alpha) / r)


def test_edges() -> None:
    with pytest.raises(ValueError):
        mann_whitney([], [1.0])
    with pytest.raises(ValueError):
        mann_whitney([1.0], [2.0], "both")
    assert mann_whitney([1.0], [2.0], exact=True) == (0.0, 1)
    assert mann_whitney([2.0, 3.0], [0.0, 1.0], "greater", exact=True) == (4.0, Fraction(1, 6))

History

Frank Wilcoxon (1945) proposed the rank-sum test for two samples of equal size, together with the signed-rank test, in a short paper. Henry Mann and Donald Whitney (1947) wrote the statistic as the pair count UU, allowed unequal sizes, gave a recursion for its null law with tables, and proved that UU is asymptotically normal under the null. Their title states the alternative that one variable is stochastically larger than the other. Hodges and Lehmann (1956) showed that the efficiency against the t-test is never below 0.8640.864 for shift models. Bamber (1975) and Hanley and McNeil (1982) linked U/(mn)U/(mn) to the area under the ROC curve.

References

  1. Myles Hollander, Douglas A. Wolfe and Eric Chicken, Nonparametric Statistical Methods, third edition, Wiley, 2014, Chapter 4 (the two-sample location problem), the section on the Wilcoxon rank sum test
  2. E. L. Lehmann, Nonparametrics, Statistical Methods Based on Ranks, revised edition, Springer, 2006, The chapter on the comparison of two treatments (the Wilcoxon rank-sum test, ties and the normal approximation)
  3. H. B. Mann and D. R. Whitney, On a test of whether one of two random variables is stochastically larger than the other, Annals of Mathematical Statistics 18(1), 1947, pp. 50 to 60 (the statistic U, its recursion and its limit law)
  4. Frank Wilcoxon, Individual comparisons by ranking methods, Biometrics Bulletin 1(6), 1945, pp. 80 to 83 (the rank-sum test for two samples of equal size)

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