Module contents
Lesson 15 of 27Core 100 min

Nonparametric tests: ranks, signs and goodness of fit

Understand rank tests, distribution-free inference, asymptotic efficiency and empirical-distribution goodness-of-fit methods, including DKW bands and QQ plots.

After this lesson you can

  • Derive sign, Wilcoxon, Mann–Whitney and Kruskal–Wallis rank tests and interpret their assumptions.
  • Connect Mann–Whitney to probability of superiority and AUC, and compare efficiency with t tests.
  • Construct a simultaneous DKW confidence band and apply ECDF goodness-of-fit tests.
  • Diagnose distributions using QQ plots and calibrate tests when parameters are estimated.

Before you start

Motivation: the outlier that silenced the t test

A team compares response time for two service versions using fourteen requests each. The new version is clearly slower on almost every request, but one suffered a network retry and took 2.4 seconds. Welch’s tt test, measuring mean difference in standard-error units, sees that request as enormous noise and finds no evidence. The next cell calculates this and varies the outlier.

[ ]A network retry that hides a regressionBrowser
import numpy as np
from scipy import stats

rng = np.random.default_rng(1)
a = np.round(rng.lognormal(4.6, 0.25, 14))      # versión actual, en ms (mediana de unos 100 ms)
b = np.round(rng.lognormal(4.95, 0.25, 14))     # versión nueva: un 40 % más lenta
print(f"medianas: A = {np.median(a):.0f} ms, B = {np.median(b):.0f} ms")

for atipico in (400.0, 2400.0, 24000.0):
    b2 = b.copy()
    b2[0] = atipico                              # una petición con reintento de red
    pt = stats.ttest_ind(b2, a, equal_var=False).pvalue
    pm = stats.mannwhitneyu(b2, a).pvalue
    print(f"atípico = {atipico:7.0f} ms | media de B = {b2.mean():7.1f} | p de Welch = {pt:.4f} | p de Mann-Whitney = {pm:.4f}")

The Mann–Whitney rank test gives the same pp value for all three outlier values, not by accident: it ignores how long the slow request took and sees only that it is largest. This lesson studies tests replacing data with ranks (positions in order), with three properties. Validity does not depend on population shape, so pp values are exact in small samples. They are insensitive to any extreme value and monotone scale change (logarithms, roots). They lose little power under normality and gain much otherwise. Six questions:

  1. Why is a rank statistic’s null distribution universal? It is a permutation test on 1,…,N1, \dots, N.
  2. What can signs of paired differences say, and what do Wilcoxon signed ranks gain?
  3. What does Mann–Whitney count? Probability of superiority, exactly classifier AUC, revealing its actual hypothesis.
  4. How does it compare with tt? Asymptotic relative efficiency: 3/π3/\pi under normality, never below 0.8640.864, above 1 once tails get heavy.
  5. How do we test a given distribution? The empirical distribution function, Dvoretzky–Kiefer–Wolfowitz confidence band, and Kolmogorov–Smirnov, Anderson–Darling and Shapiro–Wilk tests.
  6. How do we look, not just test? QQ plots.

We use hypothesis tests, permutation tests and exchangeability from the previous lesson; power function, tt tests and paired test; empirical distribution function and probability integral transform.

Ranks and their universal null distribution

Given a vector z=(z1,…,zN)z = (z_1, \dots, z_N) without repeated values, the rank of ziz_i is its position sorted from least to greatest:

Ri=#{j:zj≤zi}.R_i = \#\{j : z_j \le z_i\}.

The smallest has rank 1, largest NN. With ties, each repeated value receives the average of positions it would occupy (midranks: (3,1,2,2,5)(3, 1, 2, 2, 5) has ranks (4,1,2.5,2.5,5)(4, 1, 2.5, 2.5, 5)). A rank statistic is any function of rank vector R=(R1,…,RN)\vb{R} = (R_1, \dots, R_N).

Their convenience follows from a nearly trivial fact worth proving carefully, because everything after depends on it.

Proof

Without ties (probability 1), R\vb{R} is always a permutation of {1,…,N}\{1, \dots, N\}. Let π\pi be any permutation. Reordering variables to Z′=(Zπ(1),…,Zπ(N))Z' = (Z_{\pi(1)}, \dots, Z_{\pi(N)}) produces the same law as ZZ by exchangeability. The rank vector of Z′Z' is R\vb{R} reordered by π\pi, i.e. R∘π\vb{R}\circ\pi. Thus P(R=r)=P(R∘π=r)=P(R=r∘π−1)\Pr(\vb{R} = \vb{r}) = \Pr(\vb{R}\circ\pi = \vb{r}) = \Pr(\vb{R} = \vb{r}\circ\pi^{-1}) for every π\pi, and since r∘π−1\vb{r}\circ\pi^{-1} traverses all permutations as π\pi does, all N!N! probabilities are equal. They sum to 1, so equal 1/N!1/N!.

∎

This is the permutation-test idea with one crucial difference. Permuting raw data assigns labels over observed values, whose reference distribution must be recomputed for each dataset. A rank test assigns labels over 1,…,N1, \dots, N, the same for all datasets of that size: the null distribution is computed once, tabulated (textbook Wilcoxon and Mann–Whitney tables), and reused. Three practical consequences:

  • Exact pp values in small samples without normality or other shape assumptions, provided no ties.
  • Monotone-transform invariance. If hh is strictly increasing, ranks of h(zi)h(z_i) equal those of ziz_i. Analyzing times or their logarithms is the same test, so measurement scale need not be chosen.
  • Robustness. Changing an observation without changing its position leaves the statistic unchanged. A value can be arbitrarily distant: its influence is bounded by its rank.

The cost is discarding magnitude: ranks cannot distinguish a 1 ms difference from 1000 ms if order stays the same. The following tests use ranks by design: one sample or pairs (signs and Wilcoxon), two samples (Mann–Whitney), and kk samples (Kruskal–Wallis).

The sign test

The simplest statistical test. Given iid X1,…,XnX_1, \dots, X_n with continuous distribution, test the median: H0:mediana⁡(X)=θ0H_0: \operatorname{mediana}(X) = \theta_0. For paired data XiX_i is each pair difference. If the median is θ0\theta_0, each observation lies above with probability 1/21/2, so count them.

Proof

Indicators 1[Xi>θ0]\ind[X_i > \theta_0] are independent Bernoulli with parameter P(Xi>θ0)=1/2\Pr(X_i > \theta_0) = 1/2 (the median leaves half the probability on each side, with no mass at θ0\theta_0). Their sum is binomial.

∎

This binomial also gives a distribution-free median confidence interval. With ordered sample X(1)≤⋯≤X(n)X_{(1)} \le \dots \le X_{(n)}, median θ\theta falls below X(k+1)X_{(k+1)} exactly when at most kk observations lie below it, and above X(n−k)X_{(n-k)} when at most kk lie above. Each event has probability P(Bin(n,12)≤k)\Pr(\mathrm{Bin}(n, \tfrac12) \le k) and they are disjoint if n>2kn > 2k, so

P(X(k+1)≤θ≤X(n−k))=1−2P(Bin(n,12)≤k).\Pr\big(X_{(k+1)} \le \theta \le X_{(n-k)}\big) = 1 - 2\Pr\big(\mathrm{Bin}(n, \tfrac12) \le k\big).

With n=20n = 20 and k=5k = 5, interval [X(6),X(15)][X_{(6)}, X_{(15)}] has exact coverage 0.95860.9586 for any continuous distribution. It is conservative (coverage is discrete), but never fails the guarantee.

The sign test is most robust and least powerful: it uses only nn bits. Under normality it needs about π/2≈1.57\pi/2 \approx 1.57 times the data of tt for equal power (efficiency 2/π2/\pi below), though wins under heavy tails: for Laplace, the sign test is twice as efficient as tt.

Wilcoxon signed ranks

The sign test discards difference magnitude. Wilcoxon (1945) recovered part using ranks of absolute values: a large positive difference weighs more than a small one. Given iid differences D1,…,DnD_1, \dots, D_n (e.g. paired data), test whether centered at θ0\theta_0; without loss of generality set θ0=0\theta_0 = 0 by subtraction.

The null is stronger than for signs: not just zero median but symmetry around zero. In exchange more information is used. Pairing naturally justifies symmetry: if treatment does nothing, swapping a pair’s values leaves the data law unchanged, and difference DiD_i has the same law as −Di-D_i. This is randomization-test reasoning applied to ranks.

Proof

Symmetry makes sgn⁡(Di)\operatorname{sgn}(D_i) a uniform sign independent of ∣Di∣\abs{D_i}, and signs are independent across observations. Since RiR_i depend only on (∣D1∣,…,∣Dn∣)(\abs{D_1}, \dots, \abs{D_n}), signs are independent of all ranks. The observation ranked kk by absolute value is positive with probability 1/21/2 independently of the others and contributes kk to W+W^+ if positive: this is ∑kkBk\sum_k k B_k. Mean is 12∑k=n(n+1)/4\tfrac12\sum k = n(n+1)/4 and variance 14∑k2=n(n+1)(2n+1)/24\tfrac14\sum k^2 = n(n+1)(2n+1)/24. The coefficient of qwq^w in ∏k(1+qk)\prod_k (1 + q^k) counts subsets of {1,…,n}\{1, \dots, n\} summing to ww, satisfying recursion cn(w)=cn−1(w)+cn−1(w−n)c_n(w) = c_{n-1}(w) + c_{n-1}(w - n) (element nn is included or not). Asymptotic normality comes from the Lindeberg central limit theorem for independent nonidentical sums, since each term is bounded by nn and total variance grows as n3n^3.

∎

Ties, zeros and what is estimated

The theorem’s null distribution holds only without ties among ∣Di∣\abs{D_i} and without zeros. Real data have them (rounded measurements, integer differences), requiring explicit treatment:

  • Zeros (Di=0D_i = 0): ordinarily drop them, as in the sign test; Pratt’s method retains them when ranking and drops them afterward. Both are valid but differ: report the choice.
  • Ties among ∣Di∣\abs{D_i}: assign midranks and the exact distribution no longer applies. The normal approximation remains valid with corrected variance Var⁡(W+)=n(n+1)(2n+1)24−148∑g(tg3−tg)\Var(W^+) = \frac{n(n+1)(2n+1)}{24} - \frac{1}{48}\sum_g (t_g^3 - t_g), where tgt_g is tie-group size.

The estimator accompanying this test, as sample mean accompanies tt, is the Hodges–Lehmann estimator: the median of all Walsh averages (Di+Dj)/2(D_i + D_j)/2 with i≤ji \le j, with a confidence interval from test inversion. It estimates the pseudomedian, the median of (D1+D2)/2(D_1 + D_2)/2; under symmetry the pseudomedian equals the center.

Mann–Whitney: comparing two samples

The most practical case. Given independent X1,…,Xm∼iidFX_1, \dots, X_m \iid F and Y1,…,Yn∼iidGY_1, \dots, Y_n \iid G, ask whether XX tends to exceed YY. Pool N=m+nN = m + n observations, rank them and sum the first sample’s ranks.

The figure shows the identity underlying everything: UU is the area of a pairwise comparison matrix, and U/(mn)U/(mn) is ROC area for “classify as XX if score exceeds threshold”.

InteractiveMann–Whitney is an AUC
Two samples on an axis (drag the points)
c = 6.0X (8 datos)Y (8 datos)
The 8×88 \times 8 pairwise comparisons, with XX and YY sorted
Y increasingX increasing
  • x>yx > y (adds 1)
  • x<yx < y (adds 0)
  • tie (adds ½)
ROC curve with XX as positives (TPR: true positive rate; FPR: false positive rate); its area is U/(mn)U/(mn)
AUC 0.5AUC = 0.906
  • ROC
  • threshold cc: TPR 0.88, FPR 0.25
  • chance
Starting data
6.0
UU (pairs with x>yx > y, tie = ½) of mn=64mn = 6458.0
U/(mn)U/(mn) = area under ROC = AUC0.906
Sum of XX ranks94.0
Mann–Whitney pp (exact)0.005
Welch tt p-value0.003
Medians XX | YY7.65 | 4.70
Choosing random xx and yy, xx is greater in 91 % of pairs. The blue area in the matrix is exactly that fraction.
Drag blue points (sample XX) and orange points (sample YY). The matrix compares each xx with each yy (blue for x>yx > y, orange for x<yx < y), both samples sorted; UU counts blue cells. Right: ROC from threshold cc with XX the positive class; area is U/(mn)U/(mn), the matrix's blue fraction. Try four things. With 'One outlier', drag the extreme YY point back and forth: UU and Mann–Whitney pp change only when it crosses another point; Welch tt changes continuously. With 'Same distributions', drag one point across. With 'Equal medians, different shapes', inspect medians and area. Move the threshold along the ROC.

Null distribution and normal approximation

Under H0:F=GH_0: F = G, all NN observations are iid; by the theorem above, first-sample ranks R1,…,RmR_1, \dots, R_m are a sample without replacement of size mm from {1,…,N}\{1, \dots, N\}. This gives the full null distribution.

Proof

WW sums a size-mm sample without replacement from {1,…,N}\{1, \dots, N\}, with mean μ=(N+1)/2\mu = (N+1)/2 and variance σ2=(N2−1)/12\sigma^2 = (N^2 - 1)/12. Under sampling without replacement, E[W]=mμ\E[W] = m\mu and Var⁡(W)=mσ2(N−m)/(N−1)\Var(W) = m\sigma^2 (N - m)/(N - 1). Thus E[U]=m(N+1)/2−m(m+1)/2=mn/2\E[U] = m(N+1)/2 - m(m+1)/2 = mn/2 and

Var⁡(U)=Var⁡(W)=m⋅N2−112⋅nN−1=mn(N+1)12.\Var(U) = \Var(W) = m \cdot \frac{N^2 - 1}{12}\cdot\frac{n}{N - 1} = \frac{mn(N+1)}{12}.

The recursion conditions on which of NN observations is largest: if xx, it beats nn observations in YY and adds nn to UU (leaving m−1m - 1 in XX and nn in YY); if yy, it adds nothing (leaving mm and n−1n - 1). Asymptotic normality is the sampling-without-replacement CLT (Hájek). With ties, midranks reduce rank-population variance from (N2−1)/12(N^2 - 1)/12 to the corrected value.

∎

With m=n=8m = n = 8, the exact table gives P(U≤13)=0.0249\Pr(U \le 13) = 0.0249 and the two-sided test rejects at 5 % if U≤13U \le 13 or U≥51U \ge 51; normal approximation with continuity correction is excellent already at m,n≥8m, n \ge 8. Packages use exact distribution for small untied samples and normal otherwise.

Probability of superiority: AUC

Read the figure’s matrix as an estimate. Let θ=P(X>Y)+12P(X=Y)\theta = \Pr(X > Y) + \tfrac12\Pr(X = Y), the probability of superiority of XX over YY (psychology’s “common language effect size”). Since UU sums mnmn comparisons each with mean θ\theta, U/(mn)U/(mn) is an unbiased estimate of θ\theta (the guided proof below). In machine learning, if ff scores examples and XX are positive scores and YY negative, θ\theta is classifier AUC: the probability a random positive scores above a random negative. Mann–Whitney is AUC multiplied by mnmn, and comparing a model’s AUC with 1/21/2 (chance) is a Mann–Whitney test. This also allows AUC confidence intervals from variance of UU outside the null (DeLong’s method uses the same comparison matrix).

What hypothesis is actually tested

Under H0:F=GH_0: F = G, θ=1/2\theta = 1/2. The converse is false, causing the most common misunderstandings.

Under a shift model G(y)=F(y−Δ)G(y) = F(y - \Delta), the test concerns Δ\Delta: it tests Δ=0\Delta = 0, its natural estimate is the median of mnmn differences Xi−YjX_i - Y_j (Hodges–Lehmann), and intervals for Δ\Delta invert the test. Outside that model honestly report θ\theta (with interval) rather than “median difference”. If variances or shapes differ greatly and the target is θ=1/2\theta = 1/2, Brunner–Munzel (or Fligner–Policello), not classical Mann–Whitney, maintains level.

Kruskal–Wallis: kk samples

To compare kk groups with n1,…,nkn_1, \dots, n_k observations (N=∑ngN = \sum n_g), pool ranks RgiR_{gi} and compare each group mean rank Rˉg\bar R_g with overall (N+1)/2(N+1)/2. Equal groups should all be close.

Proof

Ranks are a permutation of {1,…,N}\{1, \dots, N\} with mean (N+1)/2(N+1)/2 and centered sum of squares N(N2−1)/12N(N^2 - 1)/12, constant regardless of data. Thus between-group rank sum of squares divided by N(N2−1)/12N(N^2-1)/12 and multiplied by N−1N - 1 is exactly HH. By the same without-replacement reasoning, Rˉg\bar R_g has mean (N+1)/2(N+1)/2, variance σ2(N−ng)/(ng(N−1))\sigma^2(N - n_g)/(n_g(N - 1)) and covariance −σ2/(N−1)-\sigma^2/(N-1) with Rˉh\bar R_h, and mean vector is asymptotically normal. HH is its quadratic form using the (generalized) inverse covariance, of rank k−1k - 1 and yielding χk−12\chi^2_{k-1}. For k=2k = 2, the result is squared (Rˉ1−(N+1)/2)/Var⁡(Rˉ1)(\bar R_1 - (N+1)/2)/\sqrt{\Var(\bar R_1)}, i.e. Mann–Whitney z2z^2.

∎

Kruskal–Wallis rejection says some group differs, not which. Locate it by pairwise Dunn tests, using pooled ranks,

zgh=Rˉg−RˉhN(N+1)12(1ng+1nh),z_{gh} = \frac{\bar R_g - \bar R_h}{\sqrt{\tfrac{N(N+1)}{12}\big(\tfrac{1}{n_g} + \tfrac{1}{n_h}\big)}},

with Holm or Bonferroni multiplicity correction (multiple comparisons). This parallels pairwise comparisons after ANOVA. Like all tests in the lesson, it detects “tends to be greater”, not “has a different mean”.

Implementation from scratch

The four tests fit in a few lines. The first cell implements midranks, exact sign test and Wilcoxon with exact null by convolution and tie-corrected normal approximation, validating against scipy.stats.

[ ]Ranks, signs and Wilcoxon from scratchBrowser
import numpy as np
from math import comb
from scipy import stats

def rangos_medios(x):
    """Rangos 1..n; los empates reciben el promedio de los rangos que ocuparían."""
    x = np.asarray(x, float)
    orden = np.argsort(x, kind="mergesort")
    s = x[orden]
    r = np.empty(len(x))
    i = 0
    while i < len(x):
        j = i
        while j + 1 < len(x) and s[j + 1] == s[i]:
            j += 1
        r[orden[i:j + 1]] = (i + j) / 2 + 1
        i = j + 1
    return r

def contraste_signos(x, mediana0=0.0):
    d = np.asarray(x, float) - mediana0
    d = d[d != 0]                                   # los ceros no informan
    n, s = len(d), int((d > 0).sum())
    k = min(s, n - s)
    return s, n, min(1.0, 2 * sum(comb(n, i) for i in range(k + 1)) / 2 ** n)

def nula_wilcoxon(n):
    """c[w] = nº de subconjuntos de {1..n} de suma w: coeficientes de prod(1 + q^k)."""
    c = np.zeros(n * (n + 1) // 2 + 1)
    c[0] = 1
    for k in range(1, n + 1):
        nuevo = c.copy()
        nuevo[k:] += c[:len(c) - k]
        c = nuevo
    return c

def wilcoxon_signo(d, exacto=None):
    d = np.asarray(d, float)
    d = d[d != 0]
    n = len(d)
    r = rangos_medios(np.abs(d))
    Wp = r[d > 0].sum()
    t = np.unique(np.abs(d), return_counts=True)[1]
    if exacto is None:
        exacto = n <= 25 and (t == 1).all()
    if exacto:
        c = nula_wilcoxon(n)
        w = int(round(Wp))
        p = min(1.0, 2 * min(c[:w + 1].sum(), c[w:].sum()) / c.sum())
    else:
        var = n * (n + 1) * (2 * n + 1) / 24 - (t ** 3 - t).sum() / 48
        z = max(0.0, abs(Wp - n * (n + 1) / 4) - 0.5) / np.sqrt(var)
        p = 2 * stats.norm.sf(z)
    return Wp, p

x = [3, 1, 2, 2, 5]
print("rangos medios:", rangos_medios(x), "| rankdata:", stats.rankdata(x))

rng = np.random.default_rng(7)
antes = rng.lognormal(5.0, 0.3, 12)
despues = antes * rng.lognormal(-0.08, 0.12, 12)       # mejora típica del 8 %
d = despues - antes
print("\ndiferencias (ms):", np.round(d, 1))
s, n, p = contraste_signos(d)
print(f"signos: S = {s} de {n}, p exacto = {p:.4f}  (scipy binomtest: {stats.binomtest(s, n, 0.5).pvalue:.4f})")
W, p = wilcoxon_signo(d)
res = stats.wilcoxon(d, method="exact")
print(f"Wilcoxon: W+ = {W:.0f}, p exacto = {p:.4f}  (scipy: W- = {res.statistic:.0f}, p = {res.pvalue:.4f})")
print(f"E[W+] = {n*(n+1)/4}, Var = {n*(n+1)*(2*n+1)/24:.2f}")

# con empates y ceros descartados: normal con corrección
d2 = np.array([1, -1, 2, 2, -3, 3, 3, 4, 5, -5, 6, 7, 7, 8, 9.0])
W2, p2 = wilcoxon_signo(d2)
print(f"\ncon empates: W+ = {W2}, p normal = {p2:.4f}  (scipy: {stats.wilcoxon(d2, method='approx', correction=True).pvalue:.4f})")

Results agree with scipy to the last digit. With the same twelve differences, sign test gives p=0.0063p = 0.0063 and Wilcoxon p=0.0010p = 0.0010. Eleven differences are negative, and the only positive (0.40.4 ms) has smallest magnitude: sign test counts it as one sign, while Wilcoxon weights magnitude, gives it rank 1, and obtains W+=1W^+ = 1, almost as extreme as possible. The second cell implements Mann–Whitney (exact distribution by memoized recursion and tie correction) and Kruskal–Wallis, checking three facts: null law under heavy tails, mean and variance of UU, and that hand-built ROC AUC is U/(mn)U/(mn).

[ ]Mann–Whitney, Kruskal–Wallis and AUC from scratchBrowser
import numpy as np
from functools import lru_cache
from scipy import stats

@lru_cache(maxsize=None)
def cuenta_u(m, n):
    """c[u] = nº de configuraciones de m x y n y (sin empates) con U = u. Recursión sobre la mayor observación."""
    if m == 0 or n == 0:
        return (1,)
    a, b = cuenta_u(m - 1, n), cuenta_u(m, n - 1)   # la mayor es una x (gana n pares) o una y (no gana ninguno)
    c = [0] * (m * n + 1)
    for u, v in enumerate(a):
        c[u + n] += v
    for u, v in enumerate(b):
        c[u] += v
    return tuple(c)

def mann_whitney(x, y, exacto=None):
    x, y = np.asarray(x, float), np.asarray(y, float)
    m, n = len(x), len(y)
    todo = np.concatenate([x, y])
    W = rangos_medios(todo)[:m].sum()
    U = W - m * (m + 1) / 2
    N = m + n
    t = np.unique(todo, return_counts=True)[1]
    if exacto is None:
        exacto = (t == 1).all() and m * n <= 400
    if exacto:
        c = np.array(cuenta_u(m, n), float)
        u = int(round(U))
        p = min(1.0, 2 * min(c[:u + 1].sum(), c[u:].sum()) / c.sum())
    else:
        var = m * n / 12 * (N + 1 - (t ** 3 - t).sum() / (N * (N - 1)))
        p = 2 * stats.norm.sf(max(0.0, abs(U - m * n / 2) - 0.5) / np.sqrt(var))
    return U, W, U / (m * n), p

def kruskal_wallis(*grupos):
    todo = np.concatenate(grupos)
    N = len(todo)
    r = rangos_medios(todo)
    medias = np.array([g.mean() for g in np.split(r, np.cumsum([len(g) for g in grupos])[:-1])])
    tam = np.array([len(g) for g in grupos])
    H = 12 / (N * (N + 1)) * (tam * (medias - (N + 1) / 2) ** 2).sum()
    t = np.unique(todo, return_counts=True)[1]
    H /= 1 - (t ** 3 - t).sum() / (N ** 3 - N)          # corrección por empates
    return H, stats.chi2.sf(H, len(grupos) - 1)

rng = np.random.default_rng(11)
x = np.round(rng.lognormal(4.9, 0.4, 9), 1)
y = np.round(rng.lognormal(4.5, 0.4, 11), 1)
U, W, auc, p = mann_whitney(x, y)
e = stats.mannwhitneyu(x, y, method="exact")
print(f"m = 9, n = 11: U = {U:.0f}, W = {W:.0f}, U/(mn) = {auc:.3f}, p exacto = {p:.4f} | scipy: U = {e.statistic:.0f}, p = {e.pvalue:.4f}")

# el AUC de la curva ROC construida a mano (x = positivos) es U/(mn)
umbrales = np.sort(np.concatenate([x, y]))[::-1]
tpr = np.r_[0, [(x >= c).mean() for c in umbrales]]
fpr = np.r_[0, [(y >= c).mean() for c in umbrales]]
print(f"área bajo la ROC (trapecios) = {np.sum(np.diff(fpr) * (tpr[1:] + tpr[:-1]) / 2):.4f}  y  U/(mn) = {auc:.4f}")

xt = np.array([1, 2, 2, 3, 5, 5, 8, 9.0])
yt = np.array([2, 3, 3, 4, 9, 10, 11.0])
print(f"con empates: p normal = {mann_whitney(xt, yt)[3]:.4f} | scipy asintótico con continuidad: {stats.mannwhitneyu(xt, yt, method='asymptotic', use_continuity=True).pvalue:.4f}")

# la ley nula no depende de F: colas de Cauchy (sin media ni varianza), m = n = 8
R, m, n = 6000, 8, 8
us = np.empty(R)
rechazos = 0
for k in range(R):
    U, _, _, p = mann_whitney(rng.standard_cauchy(m), rng.standard_cauchy(n))
    us[k] = U
    rechazos += p <= 0.05
c = np.array(cuenta_u(m, n), float)
tam_exacto = sum(c[u] for u in range(m * n + 1) if min(1.0, 2 * min(c[:u + 1].sum(), c[u:].sum()) / c.sum()) <= 0.05) / c.sum()
print(f"\nU bajo H0 con Cauchy: media {us.mean():.2f} (teoría {m*n/2}), varianza {us.var():.2f} (teoría {m*n*(m+n+1)/12:.2f})")
print(f"tamaño del test a nivel 0.05: simulado {rechazos / R:.4f}, exacto {tam_exacto:.4f}")

g1, g2, g3 = rng.lognormal(0, 1, 15), rng.lognormal(0.6, 1, 12), rng.lognormal(0.2, 1, 10)
H, pk = kruskal_wallis(g1, g2, g3)
sc = stats.kruskal(g1, g2, g3)
print(f"\nKruskal-Wallis: H = {H:.4f}, p = {pk:.4f} | scipy: H = {sc.statistic:.4f}, p = {sc.pvalue:.4f}")
H2, _ = kruskal_wallis(g1, g2)
z = (mann_whitney(g1, g2, exacto=False)[0] - 15 * 12 / 2) / np.sqrt(15 * 12 * 28 / 12)
print(f"con k = 2, H = {H2:.4f} y el z² de Mann-Whitney sin corrección de continuidad vale {z**2:.4f}")

A null-law detail: under Cauchy, which lacks even a mean, UU has exactly the theorem’s mean and variance (simulation gives 31.831.8 and 89.489.4 versus 3232 and 90.6790.67) and maintains level; exact size is 0.04990.0499, reproduced in simulation. That is distribution-freeness. (With m=n=8m = n = 8 the test is almost exactly 5 %: discreteness usually leaves actual size below nominal.)

Asymptotic relative efficiency: the cost of not assuming normality

Under normality tt is optimal (uniformly most powerful unbiased). What do ranks lose? Compare sample sizes for equal power, giving a clean limiting answer.

For asymptotically normal statistics there is a simple formula. If TiT_i has mean μi(θ)\mu_i(\theta) and standard deviation σi/n\sigma_i/\sqrt n under θ0\theta_0, its efficacy is ei=μi′(θ0)/σie_i = \mu_i'(\theta_0)/\sigma_i and ARE(T1,T2)=(e1/e2)2\mathrm{ARE}(T_1, T_2) = (e_1/e_2)^2: with local alternative θn=θ0+h/n\theta_n = \theta_0 + h/\sqrt n each test’s standardized signal is h eih\,e_i, which alone determines power. A shift test’s efficacy is its mean rise per unit shift divided by measurement noise.

θ(Δ)=P(X>Y)\theta(\Delta) = \Pr(X > Y)
With X∼f(⋅−Δ)X \sim f(\cdot - \Delta) (shifted sample) and Y∼fY \sim f, mean of U/(mn)U/(mn) is θ(Δ)=∫(1−F(y−Δ))f(y)  ⁣dy\theta(\Delta) = \int \big(1 - F(y - \Delta)\big) f(y)\,\dd y.
1/8

The 0.8640.864 bound minimizes σ2(∫f2)2\sigma^2(\int f^2)^2 over fixed-variance densities (calculus of variations): the minimum occurs at parabola f(x)∝5−x2f(x) \propto 5 - x^2 for ∣x∣<5\abs{x} < \sqrt 5. ARE can be arbitrarily large under heavy tails. Why: tt measures shift against noise σ\sigma, inflated without bound by a few extremes, while ranks use ∫f2\int f^2, driven mostly by central mass.

DistributionWilcoxon vs tt ARE\mathrm{ARE}Sign vs tt ARE\mathrm{ARE}
Uniform111/31/3
Normal3/π≈0.9553/\pi \approx 0.9552/π≈0.6372/\pi \approx 0.637
Logisticπ2/9≈1.097\pi^2/9 \approx 1.097π2/12≈0.822\pi^2/12 \approx 0.822
tt with 5 df1.2411.2410.9610.961
Laplace (double exponential)1.51.522
tt with 3 df1.9001.9001.6211.621
90 % N(0,1)\Normal(0,1) + 10 % N(0,25)\Normal(0,25)2.4122.4121.8321.832

The table quantifies gains and losses: with normals, 4.7 % more data; with t3t_3, nearly half the data. The figure simulates finite-sample versions: where each curve crosses 80 % power and the ratio of squared shifts.

InteractivePower: t versus Wilcoxon by tail weight
Power versus shift (data Laplace, n=20n = 20, 1000 simulations per point)
80 %5 %
  • Student's t
  • Wilcoxon signed-rank
  • 80% power level (points mark crossings)
Asymptotic relative efficiency of Wilcoxon versus tt
0.951.101.501.902.410.864normallogisticLaplacet with 3 dfcontaminated
  • theory 12σ2(∫f2)212\sigma^2(\int f^2)^2
  • simulated at this nn
  • Hodges–Lehmann bound 0.864
Data distribution
Sample size nn
Simulated size at δ=0\delta = 0: tt | Wilcoxon | sign4.6 % | 4.4 % | 3.6 %
Theoretical Wilcoxon efficiency versus tt (asymptotic)1.500
Simulated efficiency (δ80t/δ80W)2(\delta_{80}^t/\delta_{80}^W)^2 at this nn1.16
Theoretical sign-test efficiency versus tt2.000
With heavy tails Wilcoxon needs 33 % fewer observations than tt for the same power (efficiency 1.50). The tt measures shift against noise σ\sigma, inflated by extremes; ranks use central mass.
Simulated power curves (1000 samples per point) for tt, signed rank and optionally sign tests versus shift δ\delta in standard deviations. Points mark δ\delta at 80 % power; their squared ratio estimates ARE at this nn. Right: theoretical ARE 12σ2(∫f2)212\sigma^2(\int f^2)^2 for each family and bound 0.8640.864. Under normality tt is slightly above Wilcoxon. Switch to logistic, Laplace, tt with 3 df and contamination: curves cross and separate. Increase nn and observe noisy slow approach to theoretical ARE (at n=20n = 20 with Laplace around 1.21.2 versus asymptotic 1.51.5: ARE is a limit, not a finite-sample promise). Check that with δ=0\delta = 0 all three reject near 5 %.

One theoretical refinement: Wilcoxon is not the only rank test. Normal-score tests (van der Waerden) replace each rank by its corresponding normal quantile; Chernoff and Savage (1958) showed their ARE against tt is ≥1\ge 1 for every distribution, with equality only under normality. In this precise sense ranks “never lose” to the mean. Wilcoxon remains standard for simplicity, tables and interpretation (AUC), with efficiency never below 86.4 % (at worst 16 % more data).

Goodness of fit: the empirical distribution function

Everything so far compares samples. Another question is whether a sample is compatible with a specified distribution F0F_0 (or family such as normal). The tool is the empirical distribution function Fn(x)=1n∑i1[Xi≤x]F_n(x) = \frac1n\sum_i \ind[X_i \le x], a staircase with jumps 1/n1/n.

Glivenko–Cantelli: the whole ECDF converges

For fixed xx, Fn(x)F_n(x) is the mean of nn indicators with expectation F(x)F(x), converging by the strong law. Remarkably convergence is uniform in xx, allowing the ECDF to substitute for the entire distribution.

Proof

Proof for continuous FF (general case adapts using left limits; see probability’s Glivenko–Cantelli theorem). Fix k∈Nk \in \N and let xj=F−1(j/k)x_j = F^{-1}(j/k) for j=1,…,k−1j = 1, \dots, k-1, with x0=−∞x_0 = -\infty and xk=+∞x_k = +\infty, so F(xj)=j/kF(x_j) = j/k. For x∈[xj−1,xj]x \in [x_{j-1}, x_j], monotonicity of FnF_n and FF gives

Fn(x)−F(x)≤Fn(xj)−F(xj−1)=Fn(xj)−F(xj)+1k,Fn(x)−F(x)≥Fn(xj−1)−F(xj−1)−1k.F_n(x) - F(x) \le F_n(x_j) - F(x_{j-1}) = F_n(x_j) - F(x_j) + \tfrac1k, \qquad F_n(x) - F(x) \ge F_n(x_{j-1}) - F(x_{j-1}) - \tfrac1k.

Therefore sup⁡x∣Fn−F∣≤max⁡0≤j≤k∣Fn(xj)−F(xj)∣+1/k\sup_x\abs{F_n - F} \le \max_{0 \le j \le k}\abs{F_n(x_j) - F(x_j)} + 1/k. The strong law at the k+1k + 1 points xjx_j (finitely many) sends the maximum to 00 almost surely, so lim sup⁡nsup⁡x∣Fn−F∣≤1/k\limsup_n \sup_x\abs{F_n - F} \le 1/k almost surely. Since kk is arbitrary the limit is 00.

∎

A second fact makes the ECDF a testing tool: the law of sup⁡x∣Fn−F∣\sup_x \abs{F_n - F} does not depend on FF if FF is continuous. By the probability integral transform, Ui=F(Xi)U_i = F(X_i) are uniform on (0,1)(0, 1) and Fn(x)=Gn(F(x))F_n(x) = G_n(F(x)), where GnG_n is the ECDF of UiU_i; then sup⁡x∣Fn(x)−F(x)∣=sup⁡u∈(0,1)∣Gn(u)−u∣\sup_x\abs{F_n(x) - F(x)} = \sup_{u \in (0,1)}\abs{G_n(u) - u}. This statistic is distribution-free like ranks.

DKW inequality and confidence band

Convergence has order 1/n1/\sqrt n and an explicit bound valid for all nn.

Dvoretzky, Kiefer and Wolfowitz (1956) proved the inequality with unspecified exponential prefactor; Massart (1990) showed constant 22 works and cannot be improved because it is the first term of Kolmogorov’s limiting distribution (below). Equating the bound to α\alpha gives a band for the whole distribution function:

With α=0.05\alpha = 0.05 and n=1000n = 1000, εn=ln⁡40/2000≈0.043\eps_n = \sqrt{\ln 40/2000} \approx 0.043: with a thousand observations the unknown distribution function is within 4.34.3 percentage points of the empirical one everywhere at once. Width falls as 1/n1/\sqrt n, so halving it costs four times the data, the power-lesson law.

The key word is simultaneous. A 95 % interval for F(x)F(x) at each xx separately (pointwise band Fn(x)±1.96F(x)(1−F(x))/nF_n(x) \pm 1.96\sqrt{F(x)(1 - F(x))/n}) covers each point with probability 0.950.95, but probability of covering all points simultaneously is much lower: neighboring ECDF deviations are correlated and many points can fail. The figure measures this difference.

InteractiveThe DKW band around the ECDF
ECDF with n=3n = 3 observations and its 95 % band
n = 3
  • true FF
  • ECDF FnF_n
  • DKW band (simultaneous)
  • pointwise band Fn±zF(1−F)/nF_n \pm z\sqrt{F(1-F)/n}
Maximum distance DnD_n for this sample versus half-width εn\varepsilon_n
ε_n
Entire F coverage with n=3n = 3 (400 samples)
DKW band98.5 %pointwise band52.8 %0 %25 %50 %75 %100 %nivel 95 %
n = 3
True distribution FF
Level 1−α1 - \alpha
Sample size nn3
DKW half-width εn=ln⁡(2/α)/(2n)\varepsilon_n = \sqrt{\ln(2/\alpha)/(2n)}0.7841
Maximum distance Dn=sup⁡x∣Fn−F∣D_n = \sup_x |F_n - F|0.7175
Entire F coverage (400 replicates): DKW | pointwise98.5 % | 52.8 %
In this sample the entire true FF fits inside the band: Dn=0.717≤εn=0.784D_n = 0.717 \le \varepsilon_n = 0.784.
Press play: observations arrive one by one from true FF (thick text-colored curve), and ECDF (blue) approaches inside pink DKW band, whose width falls as 1/n1/\sqrt n. The pointwise band (dashed amber) is narrower, especially in tails, and true FF frequently leaves it. Below, 400 new samples measure how often each band contains all of FF: DKW stays near level, pointwise far below and worsening with nn as failure opportunities grow. Change the true distribution: nothing changes, since the law of sup⁡∣Fn−F∣\sup\abs{F_n - F} is independent of FF. At 90 % or 99 % level the bound is nearly exact.

The figure suggests another point: the DKW bound is not loose. The limit law of nsup⁡x∣Fn−F∣\sqrt n\sup_x\abs{F_n - F} is Kolmogorov’s, P(nDn>x)→2∑k≥1(−1)k−1e−2k2x2=2e−2x2−2e−8x2+⋯\Pr(\sqrt n D_n > x) \to 2\sum_{k\ge1}(-1)^{k-1}e^{-2k^2x^2} = 2e^{-2x^2} - 2e^{-8x^2} + \cdots. The first term is DKW; the second at α=0.05\alpha = 0.05 is order 10−610^{-6}. The 95 % DKW band is practically exact. The cell checks this and pointwise behavior by simulation.

[ ]Simultaneous coverage: DKW versus pointwise bandBrowser
import numpy as np
from scipy import stats

rng = np.random.default_rng(3)
alpha, z = 0.05, stats.norm.ppf(0.975)

def cubre(u, eps):
    """Para uniformes ordenadas (por filas): ¿contiene la banda DKW a la identidad, y la banda puntual?"""
    n = u.shape[1]
    j = np.arange(1, n + 1)
    D = np.maximum((j / n - u).max(1), (u - (j - 1) / n).max(1))        # distancia de Kolmogorov
    h = z * np.sqrt(u * (1 - u) / n)                                    # semianchura puntual en cada salto
    puntual = ((np.abs(j / n - u) <= h) & (np.abs((j - 1) / n - u) <= h)).all(1)
    return D <= eps, puntual

print("   n    eps_n   cobertura DKW   cobertura puntual")
for n in (20, 50, 200, 1000):
    u = np.sort(rng.random((4000, n)), axis=1)
    dkw, pun = cubre(u, np.sqrt(np.log(2 / alpha) / (2 * n)))
    print(f"{n:5d}  {np.sqrt(np.log(2 / alpha) / (2 * n)):.4f}     {dkw.mean():.4f}          {pun.mean():.4f}")

print(f"\nsqrt(n) * eps_n = {np.sqrt(np.log(2 / alpha) / 2):.5f}   (valor crítico de Kolmogorov al 5 %: {stats.kstwobign.isf(alpha):.5f})")
print(f"segundo término de la serie de Kolmogorov en ese punto: {2 * np.exp(-8 * np.log(2 / alpha) / 2):.1e}")

Kolmogorov–Smirnov

Invert the band into a test of H0:F=F0H_0: F = F_0 with fully specified F0F_0. Reject when F0F_0 leaves the band, i.e. maximum ECDF-to-F0F_0 distance exceeds εn\eps_n. This is Kolmogorov–Smirnov, using exact distribution of DnD_n rather than the bound.

ECDF goodness-of-fit tests share the structure of measuring distance between FnF_n and F0F_0 with a weighted norm and calibrating against its null (free of continuous F0F_0 by probability integral transform). The three most common have distinct purposes.

The first two compute F0F_0 at ordered data. For two samples, Kolmogorov–Smirnov compares ECDFs Dm,n=sup⁡t∣Fm(t)−Gn(t)∣D_{m,n} = \sup_t\abs{F_m(t) - G_n(t)}, calibrated with Kolmogorov using mn/(m+n) Dm,n\sqrt{mn/(m+n)}\,D_{m,n} (or exactly with ranks via permutation). The supremum occurs at a jump, so evaluate both ECDFs on all m+nm + n observations: sorting costs O((m+n)log⁡(m+n))\bigO((m+n)\log(m+n)). This is the coding exercise.

Estimated parameters: Lilliefors correction

F0F_0 is rarely fully known. We test “normal” or “lognormal” with mean and variance estimated from the same data. Standard Kolmogorov–Smirnov critical values then fail in a specific way: fitting parameters makes the fitted distribution closer to ECDF than a prespecified F0F_0, systematically reducing DnD_n and almost eliminating rejections.

The same applies to Anderson–Darling, whose critical values with fitted parameters differ from the simple case (for normality with fitted mean and variance, corrected A∗2=A2(1+0.75/n+2.25/n2)A^{*2} = A^2(1 + 0.75/n + 2.25/n^2) rejects at 5 % above 0.7520.752). Shapiro–Wilk does this naturally through location–scale invariance. The next cell measures level and power of four normality tests with n=50n = 50 against five alternatives.

[ ]Four normality tests: size and power with n = 50Browser
import numpy as np
from scipy import stats

def kd(x):
    """D de Kolmogorov-Smirnov contra la normal con media y desviación estimadas (por filas) y A*² de Anderson-Darling."""
    n = x.shape[1]
    s = np.sort(x, axis=1)
    F = stats.norm.cdf((s - s.mean(1, keepdims=True)) / s.std(1, ddof=1, keepdims=True))
    i = np.arange(1, n + 1)
    D = np.maximum((i / n - F).max(1), (F - (i - 1) / n).max(1))
    Fc = np.clip(F, 1e-12, 1 - 1e-12)
    A2 = -n - ((2 * i - 1) * (np.log(Fc) + np.log(1 - Fc[:, ::-1]))).sum(1) / n
    return D, A2 * (1 + 0.75 / n + 2.25 / n ** 2)

n, R = 50, 1000
rng = np.random.default_rng(3)
D0, A0 = kd(rng.normal(size=(8000, n)))
cD, cA = np.quantile(D0, 0.95), np.quantile(A0, 0.95)                 # Lilliefors y A*² por simulación
cW = np.quantile([stats.shapiro(f).statistic for f in rng.normal(size=(2000, n))], 0.05)
cKS = stats.kstwo.isf(0.05, n)                                         # tabla de Kolmogorov (parámetros conocidos)
print(f"valores críticos al 5 % con n = {n}: KS estándar {cKS:.4f}, Lilliefors {cD:.4f}, A*² {cA:.3f}, W {cW:.4f}")

alt = {
    "normal (nivel real)": lambda: rng.normal(size=(R, n)),
    "t con 3 g.l.": lambda: rng.standard_t(3, (R, n)),
    "uniforme": lambda: rng.random((R, n)),
    "exponencial": lambda: rng.exponential(size=(R, n)),
    "logística": lambda: rng.logistic(size=(R, n)),
    "mezcla 50/50, separación 3": lambda: rng.normal(size=(R, n)) + 3 * (rng.random((R, n)) < .5),
}
print(f"\n{'alternativa':28s} KS estándar  Lilliefors  Anderson-D  Shapiro-W")
for nombre, g in alt.items():
    x = g()
    D, A = kd(x)
    W = np.array([stats.shapiro(f).statistic for f in x])
    print(f"{nombre:28s} {np.mean(D > cKS):10.3f} {np.mean(D > cD):11.3f} {np.mean(A > cA):11.3f} {np.mean(W < cW):10.3f}")

Standard KS has actual size 00 and almost no power; Lilliefors calibration recovers level and some power, but Anderson–Darling and Shapiro–Wilk clearly beat it on common alternatives (heavy tails, uniform, skew), with Shapiro–Wilk best almost everywhere (n=50n = 50: 0.620.62 versus 0.580.58 for t3t_3 tails, 0.740.74 versus 0.570.57 for uniform). A mixture of populations separated by three standard deviations, clearly bimodal, is detected at most 41 % of the time at n=50n = 50 (Anderson–Darling wins there): bimodality is clearer in a histogram or QQ plot.

With large nn, everything is rejected

A fundamental problem no test solves: goodness of fit asks “is it exactly F0F_0?”, and for any real-world model the answer is no. Sufficient data detect that. A model can predict excellently yet be rejected at n=106n = 10^6.

The second practical case uses numbers. Simulate service latencies with 3 % of requests on a slow path (shifted lognormal), fit three families by maximum likelihood (gamma and Weibull shape equations solved by vectorized Newton for thousands of repetitions), and test each with Kolmogorov–Smirnov and Anderson–Darling calibrated by parametric bootstrap with refitting, using Monte Carlo pp value (1+#{Tb∗≥T})/(B+1)(1 + \#\{T^*_b \ge T\})/(B + 1).

[ ]Fitting latency: lognormal, gamma and Weibull with n = 150Browser
import numpy as np
from scipy import stats
from scipy.special import digamma, polygamma

def muestra_latencias(n, rng, q=0.03):
    """Tiempos de respuesta (ms): una lognormal principal y una fracción q que sigue un camino más lento."""
    lenta = rng.random(n) < q
    return np.where(lenta, rng.lognormal(4.7, 0.3, n), rng.lognormal(4.0, 0.3, n))

# Estimadores de máxima verosimilitud vectorizados: una fila = una muestra
def ajusta_lognormal(x):
    l = np.log(x)
    return l.mean(1), l.std(1)                                    # mu, sigma

def ajusta_gamma(x):
    s = np.log(x.mean(1)) - np.log(x).mean(1)
    k = (3 - s + np.sqrt((s - 3) ** 2 + 24 * s)) / (12 * s)       # punto de partida
    for _ in range(8):                                            # Newton sobre ln k - digamma(k) = s
        k = k - (np.log(k) - digamma(k) - s) / (1 / k - polygamma(1, k))
    return k, x.mean(1) / k                                       # forma, escala

def ajusta_weibull(x):
    lx = np.log(x)
    k = np.pi / (np.sqrt(6) * lx.std(1))
    for _ in range(12):                                           # Newton sobre la ecuación del EMV de la forma
        xk = x ** k[:, None]
        a = (xk * lx).sum(1) / xk.sum(1)
        g = a - 1 / k - lx.mean(1)
        dg = (xk * lx ** 2).sum(1) / xk.sum(1) - a ** 2 + 1 / k ** 2
        k = k - g / dg
    return k, ((x ** k[:, None]).mean(1)) ** (1 / k)

FAM = {
    "lognormal": (ajusta_lognormal, lambda x, p: stats.norm.cdf((np.log(x) - p[0][:, None]) / p[1][:, None]),
                  lambda u, p: np.exp(p[0] + p[1] * stats.norm.ppf(u))),
    "gamma":     (ajusta_gamma, lambda x, p: stats.gamma.cdf(x, p[0][:, None], scale=p[1][:, None]),
                  lambda u, p: stats.gamma.ppf(u, p[0], scale=p[1])),
    "Weibull":   (ajusta_weibull, lambda x, p: stats.weibull_min.cdf(x, p[0][:, None], scale=p[1][:, None]),
                  lambda u, p: stats.weibull_min.ppf(u, p[0], scale=p[1])),
}

def estadisticos(F):
    """Kolmogorov-Smirnov D y Anderson-Darling A² de las filas de F = cdf ajustada en los datos ordenados."""
    n = F.shape[1]
    i = np.arange(1, n + 1)
    D = np.maximum((i / n - F).max(1), (F - (i - 1) / n).max(1))
    Fc = np.clip(F, 1e-12, 1 - 1e-12)
    A2 = -n - ((2 * i - 1) * (np.log(Fc) + np.log(1 - Fc[:, ::-1]))).sum(1) / n
    return D, A2

def contraste(nombre, x, B, rng):
    """D, A² y sus valores p: ingenuo (tabla de Kolmogorov) y por bootstrap paramétrico con reajuste en cada réplica."""
    ajusta, cdf, ppf = FAM[nombre]
    xs = np.sort(x)[None, :]
    p = ajusta(xs)
    D, A2 = (v[0] for v in estadisticos(cdf(xs, p)))
    p_ingenuo = stats.kstest(x, lambda t: cdf(t[None, :], p)[0]).pvalue
    sim = ppf(rng.random((B, len(x))), p)
    sim.sort(axis=1)
    Ds, A2s = estadisticos(cdf(sim, ajusta(sim)))
    return D, A2, p_ingenuo, (1 + (Ds >= D).sum()) / (B + 1), (1 + (A2s >= A2).sum()) / (B + 1)

rng = np.random.default_rng(5)
x = muestra_latencias(150, rng)
print(f"n = {len(x)}: media {x.mean():.1f} ms, mediana {np.median(x):.1f} ms, p99 {np.quantile(x, .99):.0f} ms")
kk, _, ss = stats.gamma.fit(x, floc=0)
print(f"gamma: forma propia {ajusta_gamma(np.sort(x)[None, :])[0][0]:.4f}, scipy {kk:.4f}")

print("\nfamilia       D     p KS estándar  p KS (Lilliefors)    A²     p AD")
for nombre in FAM:
    D, A2, pi, pk, pa = contraste(nombre, x, 1000, rng)
    print(f"{nombre:10s} {D:.4f}     {pi:8.4f}         {pk:8.4f}        {A2:6.2f}  {pa:8.4f}")

At n=150n = 150 neither lognormal nor gamma is rejected (only a few requests are slow), but Weibull is; the standard Kolmogorov-table pp supplied by scipy.stats.kstest is much higher than correct. The same experiment with nn twenty times larger also rejects lognormal and gamma despite an unchanged generating mechanism.

[ ]The same fit with n = 3000: everything is rejectedBrowser
rng = np.random.default_rng(5)
x = muestra_latencias(3000, rng)
print(f"n = {len(x)}")
print("\nfamilia       D     p KS (Lilliefors)    A²      p AD   (el menor p posible con 100 réplicas es 1/101 = 0.0099)")
for nombre in FAM:
    D, A2, pi, pk, pa = contraste(nombre, x, 100, rng)
    print(f"{nombre:10s} {D:.4f}       {pk:8.4f}        {A2:7.2f}  {pa:8.4f}")

All three families are rejected, but distance DD tells another story: lognormal is 22 percentage points from ECDF at its worst point (D=0.0215D = 0.0215), gamma 44, Weibull nearly 1010. Stop asking “does it pass?” and ask “how far off, and where?” A quantile–quantile plot helps.

QQ plots: inspect the distribution, not just test it

Tests give a probability; plots show where and how fit fails. Quantile–quantile plots compare sample with theoretical quantiles.

This makes it useful: the axis is calibrated by shape, discarding mean and spread as nuisance parameters so only shape remains. Points follow a line because x(i)x_{(i)} estimates quantile F−1(pi)F^{-1}(p_i) with approximate variance p(1−p)/(nf(F−1(p))2)p(1-p)/(n f(F^{-1}(p))^2): large in tails (small density ff), small at center, so extreme points naturally move around. Draw an expected-variation band (as in the figure) rather than judging endpoints by eye.

InteractiveReading a QQ plot
Normal QQ plot (sample standardized by median and IQR)
  • ordered sample
  • line through quartiles
  • expected variation under normality (95%)
The same sample in a histogram with fitted normal
normal
  • histogram
  • normal with the same mean and variance
Population shape
0.00
1.50
0.0
Sample size nn
Skewness | excess kurtosis (sample)−0.11 | 1.78
Shapiro-Wilk: WW | pp0.9664 | 0.012
Anderson-Darling: A∗2A^{*2} | pp1.178 | 0.004
S shape: the ends deviate outward from the line (upper right and lower left). Tails are heavier than normal. Both tests reject: deviation from normality is real. The plot shows its type.
Deform a population using skewness ε\varepsilon, tail weight δ\delta (δ=1\delta = 1 is normal), and separation μ\mu of a 50/50 two-population mixture. Left: normal QQ; pink band is expected variation under normality at that nn. Right: histogram. Learn four signatures: S with outward ends (heavy tails), inverted S (light tails), arch (skew), center step (bimodality). Below: Shapiro–Wilk and Anderson–Darling. Return to 'Normal', increase nn to 1000 and slightly move ε\varepsilon or δ\delta: QQ still looks straight, but tests already reject.

Four normal-reference signatures worth remembering:

AppearanceMeaning
Straight center, ends outward: right above and left below (S)heavier tails than normal (more extremes, as in tt with few degrees of freedom)
Line with ends inward (inverted S)lighter tails (bounded, like uniform)
Arch: concave upwardpositive skew (long right tail); concave downward means negative
Step: steep center between flatter segmentsbimodality or mixture of populations; regular steps suggest discrete or rounded data

QQ plots also suggest action. Heavy tails favor robust methods or ranks (where Wilcoxon wins by ARE). Positive skew (times, prices, sizes) favors logarithms, confirmed by the log QQ. A mixture suggests separating populations. QQ-axis correlation is essentially Shapiro–Wilk: the test compresses the plot to one number, at the cost of only saying yes or no.

Using libraries

scipy.stats supplies everything here. The next cell repeats calculations with new data, comparing our earlier functions with library implementations, and adds Shapiro–Wilk, the only test not implemented by hand, and the Anderson–Darling critical-value table supplied by scipy.

[ ]scipy.stats versus our implementationsBrowser
import numpy as np
from scipy import stats

rng = np.random.default_rng(21)
a = rng.lognormal(4.6, 0.3, 40)
b = rng.lognormal(4.8, 0.5, 35)
d = a[:30] * rng.lognormal(0.05, 0.1, 30) - a[:30]

print("Wilcoxon (rangos con signo):   propio", round(wilcoxon_signo(d, exacto=False)[1], 5), "| scipy", round(stats.wilcoxon(d, method="approx", correction=True).pvalue, 5))
print("Mann-Whitney (normal):         propio", round(mann_whitney(a, b, exacto=False)[3], 5), "| scipy", round(stats.mannwhitneyu(a, b, method="asymptotic", use_continuity=True).pvalue, 5))
print("Kruskal-Wallis, 3 grupos:      propio", round(kruskal_wallis(a[:20], a[20:], b)[1], 5), "| scipy", round(stats.kruskal(a[:20], a[20:], b).pvalue, 5))

# Kolmogorov-Smirnov de una y de dos muestras
ks1 = stats.kstest((np.log(a) - np.log(a).mean()) / np.log(a).std(ddof=1), "norm")
ks2 = stats.ks_2samp(a, b)
print(f"\nKS de una muestra (parámetros estimados, p NO válido): D = {ks1.statistic:.4f}, p = {ks1.pvalue:.4f}")
print(f"KS de dos muestras: D = {ks2.statistic:.4f}, p = {ks2.pvalue:.4f}")

# normalidad de log(a): Shapiro-Wilk y Anderson-Darling (este devuelve estadístico y valores críticos)
sw = stats.shapiro(np.log(a))
ad = stats.anderson(np.log(a), "norm")
print(f"\nShapiro-Wilk de log(a): W = {sw.statistic:.4f}, p = {sw.pvalue:.4f}")
print(f"Anderson-Darling de log(a): A² = {ad.statistic:.4f}, críticos {np.round(ad.critical_values, 3)} para los niveles {ad.significance_level} %")

# y de a sin transformar: asimetría que el QQ ya mostraba
print(f"Shapiro-Wilk de a (sin log): W = {stats.shapiro(a).statistic:.4f}, p = {stats.shapiro(a).pvalue:.4f}")

Two observations. stats.anderson returns not a pp value but a statistic with critical values at 15,10,5,2.5,1 %15, 10, 5, 2.5, 1\,\% (with fitted parameters, already Lilliefors-corrected). stats.kstest with fitted parameters returns an invalid pp, as described above. For goodness of fit with estimated parameters, simulate the null as for latency.

Common mistakes

Exercises

NumericAn exact sign test
Among 17 measurement pairs an intervention improves 14 and worsens 3 (no ties). For the exact two-sided sign test of H0H_0: median difference =0= 0, what is the pp value?
NumericKruskal–Wallis from rank sums
Three groups of 5 observations each (no ties) have pooled rank sums 2020, 4040, 6060 (N=15N = 15). What is Kruskal–Wallis statistic HH?
NumericWilcoxon efficiency under normality
Calculate ARE(Wilcoxon,t)=12σ2(∫f2)2\mathrm{ARE}(\text{Wilcoxon}, t) = 12\sigma^2\big(\int f^2\big)^2 for normal N(0,σ2)\Normal(0, \sigma^2) data. Give the numerical value.
NumericDKW band half-width
With n=1000n = 1000 observations and α=0.05\alpha = 0.05, what is DKW band half-width εn=ln⁡(2/α)/(2n)\eps_n = \sqrt{\ln(2/\alpha)/(2n)}?
ProofU/(mn) is unbiased for probability of superiority
Prove: Let independent X1,…,Xm∼iidFX_1, \dots, X_m \iid F and Y1,…,Yn∼iidGY_1, \dots, Y_n \iid G, U=∑i,j(1[Xi>Yj]+121[Xi=Yj])U = \sum_{i,j}\big(\ind[X_i > Y_j] + \tfrac12\ind[X_i = Y_j]\big) and θ=P(X>Y)+12P(X=Y)\theta = \Pr(X > Y) + \tfrac12\Pr(X = Y) with independent X∼FX \sim F, Y∼GY \sim G. Then E[U/(mn)]=θ\E[U/(mn)] = \theta, without assumptions on FF and GG (not even F=GF = G).
0
Let h(x,y)=1[x>y]+121[x=y]h(x, y) = \ind[x > y] + \tfrac12\ind[x = y], so U=∑i=1m∑j=1nh(Xi,Yj)U = \sum_{i=1}^m\sum_{j=1}^n h(X_i, Y_j).

Step 1 of 4. What can be said about the law of each (Xi,Yj)(X_i, Y_j)?

CodeTwo-sample Kolmogorov–Smirnov and DKW band
Complete two functions. ks_dos_muestras(x, y) returns two-sample Kolmogorov–Smirnov statistic D=sup⁡t∣Fm(t)−Gn(t)∣D = \sup_t\abs{F_m(t) - G_n(t)} in O((m+n)log⁡(m+n))\bigO((m+n)\log(m+n)): the supremum occurs at a jump, so evaluate both right-continuous ECDFs on all m+nm + n pooled values using np.searchsorted(..., side='right'). It must handle ties. banda_dkw(n, alpha) returns half-width εn=ln⁡(2/α)/(2n)\eps_n = \sqrt{\ln(2/\alpha)/(2n)}. Tests compare with scipy.stats.ks_2samp.
import numpy as np

def ks_dos_muestras(x, y):
  """D = sup_t |F_m(t) - G_n(t)| con coste O((m + n) log(m + n))."""
  x, y = np.sort(x), np.sort(y)
  # tu código: evalúa las dos ECDF en todos los datos y toma el máximo de la diferencia absoluta
  return 0.0

def banda_dkw(n, alpha=0.05):
  """Semianchura epsilon de la banda DKW de nivel 1 - alpha."""
  return 0.0
Shift+Enter to run
QuizSignificant Mann–Whitney with equal medians
Two service versions each have 200 request measurements. Sample medians are identical (120 ms each). Mann–Whitney gives U/(mn)=0.38U/(mn) = 0.38 (B versus A) and p<0.001p < 0.001. Which conclusions are valid?

More than one answer may be correct.

QuizKolmogorov–Smirnov with estimated mean and deviation
An analyst tests normality of n=60n = 60 observations using scipy.stats.kstest on data standardized with their own mean and standard deviation, obtaining D=0.14D = 0.14 and p=0.17p = 0.17. What follows?

Summary

Key idea
A rank test permutes 1,…,N1, \dots, N: its null law is identical for every population, invariant to monotone transforms and insensitive to outliers, losing little power under normality (3/π3/\pi) while gaining much with heavy tails. For goodness of fit, ECDF converges uniformly and the simultaneous, nearly exact DKW band quantifies uncertainty.
  • Ranks. Exchangeable untied data have rank vector uniform over N!N! permutations: rank statistics are distribution-free, exact in small samples and invariant to monotone transforms.
  • Signs and Wilcoxon. The sign test concerns median and is Bin(n,1/2)\mathrm{Bin}(n, 1/2) without further assumptions. Signed ranks sum ∑kkBk\sum_k kB_k under symmetry, mean n(n+1)/4n(n+1)/4, variance n(n+1)(2n+1)/24n(n+1)(2n+1)/24. Treat zeros and ties explicitly.
  • Mann–Whitney. UU counts mnmn pairwise comparisons and U/(mn)U/(mn) unbiasedly estimates P(X>Y)+12P(X=Y)\Pr(X > Y) + \tfrac12\Pr(X = Y), AUC. It tests stochastic superiority, not medians. Under H0H_0: mean mn/2mn/2, variance mn(m+n+1)/12mn(m+n+1)/12.
  • Kruskal–Wallis. HH is ANOVA on ranks, asymptotically χk−12\chi^2_{k-1}; for k=2k = 2 it is Mann–Whitney z2z^2. Pairwise comparisons use Dunn and multiplicity correction.
  • ARE. ARE(Wilcoxon,t)=12σ2(∫f2)2\mathrm{ARE}(\text{Wilcoxon}, t) = 12\sigma^2(\int f^2)^2: 3/π≈0.9553/\pi \approx 0.955 for normals, at least 0.8640.864 always, 1.51.5 for Laplace and 1.91.9 for t3t_3. Sign versus tt: 2/π2/\pi under normality.
  • Goodness of fit. Glivenko–Cantelli: distance sup⁡∣Fn−F∣\sup\abs{F_n - F} is distribution-free, and DKW band εn=ln⁡(2/α)/(2n)\eps_n = \sqrt{\ln(2/\alpha)/(2n)} is simultaneous and nearly exact (unlike pointwise). Kolmogorov–Smirnov monitors center, Anderson–Darling tails, and Shapiro–Wilk is most powerful for normality. Fit parameters require simulated calibration (Lilliefors); at large nn everything is rejected, and QQ shows how and where.