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
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Frank Wilcoxon, Henry B. Mann, Donald R. Whitney, 1945
The Mann-Whitney U test compares two independent samples and . Its statistic counts the pairs with , with ties counted as one half. Equivalently, rank the pooled sample and add the ranks of the values: this rank sum is Wilcoxon's statistic, and . Under the null hypothesis that both samples come from the same distribution, every choice of which of the pooled values form the first sample is equally likely, so has an exact law that a dynamic program counts. estimates , the area under the ROC curve, and the test is consistent exactly against alternatives where this value differs from .
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. are independent with distribution , and are independent with distribution , independent of the values.
Hypotheses. : . The alternatives are about : "greater" is (the values tend to be larger), "less" is , and two-sided is . In the shift model these are , and .
Statistic. . With midranks of the values in the pooled sample, .
Null distribution. Exact and conditional on the pooled values. Under the values are exchangeable, so given the multiset of pooled values, each of the ways to choose the positions of the first sample has probability . The mean of is and the variance is , with the sizes of the tie groups. Without ties the law is symmetric about ; with ties it can be asymmetric.
P-values. With the number of choices that give and :
- Greater: .
- Less: .
- Two-sided: . Without ties this equals .
Rejection rule and size. Reject at level when . The size is at most for every and , conditionally on the tie pattern and therefore also overall.
Sensitivity and power. converges to , so the test is consistent against every alternative with and against no alternative with . When but , the rejection rate can be far from in either direction (see Properties). In the shift model its asymptotic efficiency against the two-sample t-test is for normal data and at least for every continuous law (Hodges and Lehmann 1956), the same values as for the signed-rank test.
The algorithm
MANN-WHITNEY(x_1, ..., x_m, y_1, ..., y_n, alternative)- 1
r ← 2 · (midranks of the pooled values x_1, ..., x_m, y_1, ..., y_n) ▷ integers - 2
u ← (r_1 + ... + r_m) - m(m + 1) ▷ u = 2U - 3
k ← min(m, n); c[j][s] ← 0 for all j, s; c[0][0] ← 1 - 4
for each pooled value i - 5
for j ← k down to 1, for s ← top down to r_i: c[j][s] ← c[j][s] + c[j - 1][s - r_i] - 6
map each s with c[k][s] > 0 to 2U: s - m(m + 1) if k = m, else 2mn - (s - n(n + 1)) - 7
A ← number of choices with 2U ≥ u; B ← number with 2U ≤ u - 8
return 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 is the largest sum of doubled ranks. After line L5 has processed all values, is the number of -element sets of positions whose doubled ranks add up to . This is the count of subsets by their sum with one more index for the size. Counting subsets of the smaller size keeps the table small; if the counted set is the second sample, and line L6 converts its rank sum to of the first sample through . Doubled midranks keep every index an integer, so the counts are exact even with ties. The code returns and the p-value, and also offers the normal approximation with the tie-corrected variance and a continuity correction of .
Example
Two small samples. Take and , so , . In the pooled order the values have ranks , , and ; the two values share the midrank . So and out of . Counting pairs gives the same: beats one , and beat all five, and beats four and ties one. Lines L3 to L7 over the choices give with , so the one-sided p-value is and the two-sided p-value is . The normal approximation gives and with the continuity correction, and and without it. The estimate of is .
A null law. For , without ties, the 10 choices give with counts , symmetric about .
Ties break the symmetry. For pooled ranks and , the 10 choices give with counts . The mean is still , 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 .
Correctness
The proof is in proofs/correctness.md. Under the pooled sample is exchangeable, so given the multiset of values all position sets for the first sample are equally likely. depends on the position set only through the sum of its ranks. After all values pass line L5, counts the -sets with doubled rank sum , by the same include-or-exclude induction as for subset sums. Line L6 maps each sum to , 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 , let be the pooled values with the values first, and let be their doubled midranks (line L1).
Claim 1 (U from ranks). , as line L2 computes.
Proof. The midrank of is . Sum over and split the pooled values into values and values. The part gives , because each unordered pair of values contributes exactly 1 (either one is smaller, or both get ). The part gives . So .
Claim 2 (the null law). Under , conditional on the multiset of pooled values, the set of positions (in the sorted pooled order) taken by the values is uniform over the subsets of size , and .
Proof. Under the 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 slots that is consistent with it has the same conditional probability, so the set of slots holding the first variables is uniform. Midranks are functions of the multiset, so Claim 1 gives the formula.
Claim 3 (the table). After line L5 has processed the values , is the number of -element sets with , for and .
Proof. Induction on . At the start only the empty set exists, so and every other entry is 0. A -set inside either leaves out (counted by the old ) or is for a -set with sum (counted by the old ). Line L5 runs downward, so is still the old row when is updated; row never changes, which is correct because only the empty set has size 0. Every sum of doubled ranks is at most , so no count is lost.
Claim 4 (the conversion). Line L6 gives the number of size- sets with .
Proof. If , apply Claim 2 directly to . If , the complement is an -set, and is a bijection. The pairs split into , and , so , and Claim 1 for the sample gives . So with .
Claim 5 (validity). Lines L7 and L8 return , and the doubled smaller tail of the conditional null law, and for every , .
Proof. By Claims 2 to 4, and are the exact conditional tails. For a one-sided p-value, the rejection set is empty or an upper set with least element , and its conditional probability is ; the lower tail is the same. For the two-sided p-value, forces one tail to be at most , and each such event has conditional probability at most . This needs no symmetry, so it holds with ties. Averaging over the multiset of pooled values gives the unconditional bound.
Claim 6 (symmetry without ties). If the values are distinct, .
Proof. Without ties . The map is a bijection on -sets and sends the doubled rank sum to , hence to .
With ties the reflection changes the tie pattern, and the law can be asymmetric; the tests give an example with ranks .
Moments. Under the uniform law of , , so . Sampling of values without replacement, . Without ties , and a tie group of size lowers it by . This gives the variance on the page; the tests check it in exact fractions.
Cost. With , . Line L5 does at most additions for each pair with and , so , because . For distinct values the inner range has length , which is when , so the bound is tight. The table has entries.
Complexity
Line L1 sorts in with . Let . The largest doubled rank sum of values is , so the table has entries, which is . Line L5 does additions for each of the values of and each of the values of , so the time is additions. For the exact p-value took s of CPU time in the Python code. The classic recursion of Mann and Whitney on the counts by has the same order. For large samples the normal approximation costs .
Properties
- Distribution-free. Under the conditional law depends only on , and the tie pattern.
- Invariant. does not change under any increasing transformation applied to both samples.
- Connection to AUC. is the empirical area under the ROC curve of a score that separates the two samples, and is a two-sample U-statistic with kernel .
- Not a test of medians. With and , and exponential with mean 1, both medians are 0 but . A Monte Carlo run with , samples and seed 21 rejected at in of samples, with the normal approximation.
- Unequal spreads. With , , but . With , , samples and seed 22, the test rejected in of samples at the nominal . With the spreads exchanged ( with standard deviation 4, with standard deviation 1) and seed 23 it rejected in . The test does not control the size for this problem.
Variants and improvements
- Rank-sum form. Wilcoxon's gives the same p-values.
- Normal approximation. with the tie-corrected above. For the example it gave against the exact .
- Estimator and interval. The Hodges-Lehmann estimator of the shift is the median of the differences , and inverting the test gives an interval between two order statistics of these differences.
- Unequal spreads. The Brunner-Munzel test estimates the variance of under without assuming , and so keeps the size approximately when the spreads differ.
- Several samples. The Kruskal-Wallis test extends the rank sum to groups; for its statistic is the square of the of this test without the continuity correction.
- Other two-sample tests. The two-sample Kolmogorov-Smirnov test reacts to any difference between and , 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 . For paired data use the signed-rank test.
Pitfalls
- It is not a test of medians or means. Equal medians gave a rejection rate in the Monte Carlo run above.
- Unequal spreads. With but , the size was or at the nominal , depending on which sample is the smaller one.
- Conventions for . Some books and programs report , which is , or the smaller of the two, or the rank sum . 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.
# 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 , allowed unequal sizes, gave a recursion for its null law with tables, and proved that 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 for shift models. Bamber (1975) and Hanley and McNeil (1982) linked to the area under the ROC curve.
References
- 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
- 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)
- 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)
- 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.
| 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 9WF4CP Edit this page History Report an error Markdown