Algorithm Search⌘K

Algorithmcore

Kolmogorov-Smirnov test

Also called KS test, Kolmogorov-Smirnov statistic.

Tests whether a sample comes from a given distribution, or two samples from the same one, by the largest distance between distribution functions.

Time
Θ(n^3 log n) worstΘ(n log n) best
Space
Θ(n^2) extra
Where
d = the observed statistic D; n = the sample size
Properties
deterministicexactofflineiterative
Origin
Andrey Kolmogorov, Nikolai Smirnov, 1933

The Kolmogorov-Smirnov test checks whether a sample x1,…,xnx_1, \ldots, x_n comes from a given continuous distribution function F0F_0. Its statistic is the largest vertical distance Dn=sup⁡t∣Fn(t)−F0(t)∣D_n = \sup_t \lvert F_n(t) - F_0(t) \rvert between the empirical distribution function FnF_n and F0F_0. After sorting, DnD_n is the largest of 2n2n simple differences. Under the null hypothesis the law of DnD_n is the same for every continuous F0F_0, so one exact law serves all models. The page computes this law with the matrix method of Marsaglia, Tsang and Wang, and uses a one-sided finite sum when the tail is small. The two-sample form compares two empirical distribution functions and counts lattice paths for its exact p-value.

In plain words

A model says how the data should spread out. Sort the data and draw the curve that rises by one step at each data point, from zero to one. Draw the curve of the model on the same picture. If the model is right, the two curves stay close. The test measures the largest vertical gap between them and asks how often a gap this large comes from data that really follow the model.

The answer is the same for every continuous model, because a fixed change of scale turns any such model into the uniform model on zero to one. So one table, or one exact computation, serves every model. Two samples are compared in the same way, with the curve of each sample in place of the model.

The problem

Model. X1,…,XnX_1, \ldots, X_n are independent with an unknown distribution function FF. F0F_0 is a fully specified continuous distribution function.

Hypotheses. H0H_0: F=F0F = F_0. Two-sided H1H_1: F≠F0F \ne F_0. One-sided "greater": F(t)>F0(t)F(t) > F_0(t) for some tt. One-sided "less": F(t)<F0(t)F(t) < F_0(t) for some tt.

Statistic. With ui=F0(x(i))u_i = F_0(x_{(i)}) for the sorted data,

D+=sup⁡t(Fn(t)−F0(t))=max⁡i(in−ui),D−=sup⁡t(F0(t)−Fn(t))=max⁡i(ui−i−1n),D^+ = \sup_t (F_n(t) - F_0(t)) = \max_i \left(\frac{i}{n} - u_i\right), \qquad D^- = \sup_t (F_0(t) - F_n(t)) = \max_i \left(u_i - \frac{i - 1}{n}\right),

and D=max⁡(D+,D−)D = \max(D^+, D^-). The one-sided tests use D+D^+ or D−D^-.

Null distribution. Exact. If F0F_0 is continuous, Ui=F0(Xi)U_i = F_0(X_i) is uniform on (0,1)(0, 1) under H0H_0, and DD, D+D^+ and D−D^- are functions of the UiU_i only. So their laws depend on nn and not on F0F_0. D+D^+ and D−D^- have the same law, P(D+≥d)=d∑j=0⌊n(1−d)⌋(nj)(1−d−jn)n−j(d+jn)j−1P(D^+ \ge d) = d \sum_{j=0}^{\lfloor n(1-d) \rfloor} \binom{n}{j} \left(1 - d - \frac{j}{n}\right)^{n-j} \left(d + \frac{j}{n}\right)^{j-1} for 0<d≤10 < d \le 1. The two-sided law P(D<d)P(D < d) has no short closed form; line L8 computes it exactly. As n→∞n \to \infty, P(nD>λ)→2∑k≥1(−1)k−1e−2k2λ2P(\sqrt{n} D > \lambda) \to 2 \sum_{k \ge 1} (-1)^{k-1} e^{-2k^2\lambda^2}, the Kolmogorov distribution, and P(nD+>λ)→e−2λ2P(\sqrt{n} D^+ > \lambda) \to e^{-2\lambda^2}.

P-values. For an observed value dd the two-sided p-value is P(D≥d)P(D \ge d), and the one-sided p-values are P(D+≥d+)P(D^+ \ge d^+) and P(D−≥d−)P(D^- \ge d^-). No doubling rule is needed: DD is already two-sided. For d≥1/2d \ge 1/2 the events D+≥dD^+ \ge d and D−≥dD^- \ge d cannot both happen, so P(D≥d)=2P(D+≥d)P(D \ge d) = 2P(D^+ \ge d) exactly. For every dd, P(D≥d)≤2P(D+≥d)P(D \ge d) \le 2 P(D^+ \ge d).

Rejection rule and size. Reject at level α\alpha when p≤αp \le \alpha. For continuous F0F_0 the exact p-value gives size α\alpha when α\alpha is a value of the tail function, and at most α\alpha always. The exact 5% critical values of DD are 0.56330.5633, 0.40920.4092, 0.29410.2941, 0.18840.1884 and 0.13400.1340 for n=5,10,20,50,100n = 5, 10, 20, 50, 100. The limit gives 1.3581/n1.3581/\sqrt{n}, that is 0.60740.6074, 0.42950.4295, 0.30370.3037, 0.19210.1921 and 0.13580.1358, so the limit test is conservative for small nn.

Sensitivity and power. The test is consistent against every fixed F≠F0F \ne F_0, because Dn→sup⁡t∣F(t)−F0(t)∣>0D_n \to \sup_t \lvert F(t) - F_0(t) \rvert > 0 by the Glivenko-Cantelli theorem. The statistic is a sup over all tt, and the variance of Fn(t)F_n(t) is largest near the median of F0F_0, so the test reacts most to differences in the middle of the distribution and least to differences in the tails. In a Monte Carlo run against F0=N(0,1)F_0 = N(0, 1) with n=20n = 20, r=2000r = 2000 samples per case and α=0.05\alpha = 0.05, it rejected 51.55%51.55\% of samples from N(0.5,1)N(0.5, 1) (seed 62) and 17.5%17.5\% of samples from N(0,1.52)N(0, 1.5^2) (seed 63).

The algorithm

The pseudocode gives the one-sample two-sided test. Here SMIRNOV(n,d)\mathrm{SMIRNOV}(n, d) is the finite sum for P(D+≥d)P(D^+ \ge d) above, and indices of the m×mm \times m matrix HH run from 1.

  1. KOLMOGOROV-SMIRNOV(x_1, ..., x_n, F_0)
  2. 1sort x; u_i ← F_0(x_(i)) for i = 1, ..., n
  3. 2D+ ← max_i (i/n - u_i); D- ← max_i (u_i - (i - 1)/n); D ← max(D+, D-)
  4. 3if D ≥ 1/2 or 2 · SMIRNOV(n, D) < 10^-3 then return D, min(1, 2 · SMIRNOV(n, D))
  5. 4k ← ⌊nD⌋ + 1; h ← k - nD; m ← 2k - 1
  6. 5H[i][j] ← 1/(i - j + 1)! if i - j + 1 ≥ 0, else 0, for 1 ≤ i, j ≤ m
  7. 6H[i][1] ← H[i][1] - h^i/i!; H[m][j] ← H[m][j] - h^(m-j+1)/(m-j+1)!; H[m][1] ← H[m][1] + max(0, 2h - 1)^m/m!
  8. 7T ← H^n by repeated squaring, rescaling every product by a power of 2
  9. 8return D, 1 - (n!/n^n) · T[k][k]

Lines L1 and L2 compute the statistic: between two data points FnF_n is constant and F0F_0 is nondecreasing, so the sup of each difference is reached at a data point or just before it. Line L3 handles two cases with the one-sided sum. For D≥1/2D \ge 1/2 the doubled one-sided tail is the exact two-sided tail. For a small tail the doubled one-sided tail is an upper bound whose relative excess is tiny; the code measured 8.1×10−128.1 \times 10^{-12} at n=20n = 20, d=0.4d = 0.4 and 1.7×10−111.7 \times 10^{-11} at n=40n = 40, d=0.3d = 0.3. Line L3 avoids 1−P(D<d)1 - P(D < d) there, because that subtraction loses the digits of a small tail: the float error of line L8 was 1.1×10−81.1 \times 10^{-8} at n=40n = 40, d=0.45d = 0.45 and 1.1×10−51.1 \times 10^{-5} at n=60n = 60, d=0.4d = 0.4. Lines L4 to L8 are the matrix method. The state is how far the count of data points runs ahead of or behind the model line, measured at the steps 1/n1/n, and HH holds the transition weights of one step; line L6 removes the paths that leave the band inside a step. The rescaling of line L7 keeps the entries of HnH^n in the float range. The code also returns the one-sided p-values from the sum, and the asymptotic p-value from the Kolmogorov series. By default it is exact for n≤100n \le 100.

Two samples. For samples of sizes mm and nn with distribution functions FmF_m and GnG_n, the statistic is Dm,n=sup⁡t∣Fm(t)−Gn(t)∣D_{m,n} = \sup_t \lvert F_m(t) - G_n(t) \rvert. Walk through the merged sorted values; after ii values of the first sample and jj values of the second, Fm−Gn=(in−jm)/(mn)F_m - G_n = (in - jm)/(mn). So Dm,n=t/(mn)D_{m,n} = t/(mn) with tt the largest ∣in−jm∣\lvert in - jm \rvert at the end of each block of equal values. Under H0H_0 without ties, the order of the labels is uniform over the (m+nm)\binom{m+n}{m} lattice paths from (0,0)(0, 0) to (m,n)(m, n). A dynamic program counts the paths that keep ∣in−jm∣<t\lvert in - jm \rvert < t at every point, and the p-value is one minus their share, in exact integers.

Example

One sample. The model is the exponential law with mean 1, F0(t)=1−e−tF_0(t) = 1 - e^{-t}. The data are 0.42,0.06,1.95,0.88,0.13,3.10,0.27,0.71,0.09,0.350.42, 0.06, 1.95, 0.88, 0.13, 3.10, 0.27, 0.71, 0.09, 0.35, so n=10n = 10. After sorting, line L1 gives

u=(0.0582,0.0861,0.1219,0.2366,0.2953,0.3430,0.5084,0.5852,0.8577,0.9550).u = (0.0582, 0.0861, 0.1219, 0.2366, 0.2953, 0.3430, 0.5084, 0.5852, 0.8577, 0.9550).

Line L2 gives D+=6/10−0.3430=0.2570D^+ = 6/10 - 0.3430 = 0.2570 at i=6i = 6 and D−=0.0582D^- = 0.0582 at i=1i = 1, so D=0.2570D = 0.2570. The two-sided tail is not small, so lines L4 to L8 run with k=3k = 3, h=0.4295h = 0.4295 and a 5×55 \times 5 matrix, and give the exact p=0.4493p = 0.4493. The one-sided p-values are 0.22670.2267 for "greater" and 0.90310.9031 for "less", and the asymptotic two-sided p-value is 0.52340.5234. The data are compatible with the model. Against the exponential law with mean 0.50.5 the same data give D=D−=0.1798D = D^- = 0.1798 and p=0.8484p = 0.8484, so the test does not separate the two models with ten points.

The exact law against the limit. For n=10n = 10, d=0.3d = 0.3, the exact tail is 0.27050.2705 and the limit gives 0.32910.3291; the bound 2⋅SMIRNOV2 \cdot \mathrm{SMIRNOV} gives 0.27090.2709. At n=10n = 10, d=0.41d = 0.41, which is above the exact 5% point, the exact tail 0.049320.04932 equals 2⋅SMIRNOV2 \cdot \mathrm{SMIRNOV} to the digits shown, while the limit gives 0.06930.0693. At n=100n = 100, d=0.134d = 0.134 the exact tail is 0.050080.05008 and the limit gives 0.055130.05513.

Two samples. Take x=1.2,3.4,2.2,5.1,4.4,3.9x = 1.2, 3.4, 2.2, 5.1, 4.4, 3.9 and y=0.3,1.1,2.0,0.9,1.7,2.5,0.5y = 0.3, 1.1, 2.0, 0.9, 1.7, 2.5, 0.5, so m=6m = 6, n=7n = 7. After the value 2.02.0, one xx and six yy values are passed, so G7−F6=6/7−1/6=29/42G_7 - F_6 = 6/7 - 1/6 = 29/42, the largest gap. The path count finds 116116 of the (136)=1716\binom{13}{6} = 1716 label orders with a gap of at least 29/4229/42, so p=116/1716=0.0676p = 116/1716 = 0.0676. The limit gives 0.09190.0919.

Correctness

The proof is in proofs/correctness.md. The probability integral transform makes the null law of (u1,…,un)(u_1, \ldots, u_n) that of uniform order statistics. Lines L1 and L2 compute the sup because FnF_n is a step function and F0F_0 is monotone. D<dD < d means that every u(i)u_{(i)} lies in the open interval (i/n−d,(i−1)/n+d)(i/n - d, (i-1)/n + d). Embed the uniforms in a Poisson process: then this event is a band condition on a Markov chain observed at the steps 1/n1/n, the band has 2k−12k - 1 integer states, and HH is ee times the one-step transition matrix inside the band, with line L6 subtracting the paths that leave the band within a step. The sum for D+D^+ follows from the ballot theorem. For d≥1/2d \ge 1/2 the two one-sided events are disjoint, and for smaller dd the doubled one-sided tail is an upper bound, so every p-value is exact or conservative, and the test has size at most α\alpha.

Proof: The Kolmogorov-Smirnov statistic, its exact null law, and why the p-values are validfull

We use the pseudocode of the page. F0F_0 is continuous, ui=F0(x(i))u_i = F_0(x_{(i)}), and c=ndc = nd with k=⌊c⌋+1k = \lfloor c \rfloor + 1 and h=k−c∈(0,1]h = k - c \in (0, 1], as in line L4.

Claim 1 (the statistic). Lines L1 and L2 return D+=sup⁡t(Fn(t)−F0(t))D^+ = \sup_t (F_n(t) - F_0(t)) and D−=sup⁡t(F0(t)−Fn(t))D^- = \sup_t (F_0(t) - F_n(t)).

Proof. On [x(i),x(i+1))[x_{(i)}, x_{(i+1)}) the function FnF_n equals i/ni/n (or more, at tied points, which only raises the value at the last index of the tie) and F0F_0 is nondecreasing, so sup⁡(Fn−F0)\sup (F_n - F_0) on this interval is i/n−uii/n - u_i. Before x(1)x_{(1)}, Fn−F0≤0≤1−unF_n - F_0 \le 0 \le 1 - u_n. So D+=max⁡i(i/n−ui)D^+ = \max_i (i/n - u_i). On [x(i−1),x(i))[x_{(i-1)}, x_{(i)}), Fn=(i−1)/nF_n = (i-1)/n and sup⁡F0=F0(x(i)−)=ui\sup F_0 = F_0(x_{(i)}-) = u_i by continuity, which gives ui−(i−1)/nu_i - (i-1)/n. After x(n)x_{(n)}, F0−Fn≤0F_0 - F_n \le 0. □\square

Claim 2 (distribution-free). Under H0H_0, (u1,…,un)(u_1, \ldots, u_n) has the law of the order statistics U(1)<⋯<U(n)U_{(1)} < \cdots < U_{(n)} of nn independent uniforms on (0,1)(0, 1). So the laws of DD, D+D^+ and D−D^- depend only on nn, and D+D^+ and D−D^- have the same law.

Proof. For continuous F0F_0, P(F0(X)≤s)=sP(F_0(X) \le s) = s for s∈[0,1]s \in [0, 1], so F0(Xi)F_0(X_i) is uniform, and F0F_0 is nondecreasing, so it maps the sorted data to the sorted uniforms. By Claim 1 the statistics are functions of these values. The map Ui↦1−UiU_i \mapsto 1 - U_i keeps the joint law and turns max⁡i(i/n−U(i))\max_i (i/n - U_{(i)}) into max⁡j(U(j)′−(j−1)/n)\max_j (U'_{(j)} - (j-1)/n) with j=n+1−ij = n + 1 - i, so it exchanges D+D^+ and D−D^-. □\square

Claim 3 (the band). D<dD < d if and only if i/n−d<U(i)<(i−1)/n+di/n - d < U_{(i)} < (i-1)/n + d for every ii.

Proof. This is Claim 1: D+<dD^+ < d means i/n−U(i)<di/n - U_{(i)} < d for all ii, and D−<dD^- < d means U(i)−(i−1)/n<dU_{(i)} - (i-1)/n < d for all ii. □\square

Claim 4 (the matrix formula). P(D<d)=n!nn(Hn)kkP(D < d) = \frac{n!}{n^n} (H^n)_{kk} with HH from lines L5 and L6.

Proof. Let NN be a Poisson process of rate 1 on [0,n][0, n] with jump times S1<S2<⋯S_1 < S_2 < \cdots. Given N(n)=nN(n) = n, the points Si/nS_i / n are distributed as U(1),…,U(n)U_{(1)}, \ldots, U_{(n)}. By Claim 3, D<dD < d becomes the event EE that i−c<Si<i−1+ci - c < S_i < i - 1 + c for i=1,…,ni = 1, \ldots, n. Let V(s)=N(s)−sV(s) = N(s) - s. Between jumps VV falls at slope 1, and at a jump it rises by 1. The condition Si>i−cS_i > i - c says that VV stays below cc just after each jump, and Si<i−1+cS_i < i - 1 + c says that VV stays above −c-c just before each jump. So EE is the event that V(s)<cV(s) < c and V(s−)>−cV(s-) > -c for all s∈[0,n]s \in [0, n].

At integer times VV is an integer. Take first h<1h < 1; then k−1<c<kk - 1 < c < k, and ∣V∣<c\lvert V \rvert < c allows the m=2k−1m = 2k - 1 values k−1,…,−(k−1)k - 1, \ldots, -(k-1). Give the value vv the index i=k−vi = k - v, so i=1i = 1 is the top value k−1k - 1 and i=mi = m is the bottom value −(k−1)-(k-1). A step from time ss to s+1s + 1 from index ii to index jj needs exactly i−j+1i - j + 1 jumps, which has probability e−1/(i−j+1)!e^{-1}/(i - j + 1)!, or 0 if i−j+1<0i - j + 1 < 0. This is e−1e^{-1} times the entry of line L5.

Now remove the steps that leave the band between integer times. Suppose that VV reaches cc at a time τ\tau inside the step. After τ\tau it falls by at most 1−τ1 - \tau, so the end value is at least c−1+τ=k−h−1+τc - 1 + \tau = k - h - 1 + \tau. For an end value of at most k−2k - 2 this needs τ≤h−1≤0\tau \le h - 1 \le 0, which is not possible. So upper exits happen only in steps that end at index 1, and then only with τ≤h\tau \le h. A step from index ii to index 1 has ii jumps. With JJ jumps by time τ\tau, VV reaches cc when J−τ≥i−hJ - \tau \ge i - h, and J≤iJ \le i, so all ii jumps must be in [0,h][0, h]. That has probability e−hhi/i!⋅e−(1−h)=e−1hi/i!e^{-h} h^i / i! \cdot e^{-(1-h)} = e^{-1} h^i / i!. In the same way, VV reaches −c-c from the start value vv before the first jump at time τ\tau when v−τ≤−cv - \tau \le -c, that is τ≥v+k−h\tau \ge v + k - h. This is possible inside a step only for v=−(k−1)v = -(k-1), the index mm, and then exactly when no jump falls in [0,1−h][0, 1 - h]. After a jump, VV is at least v+1−τ>−cv + 1 - \tau > -c. A step from index mm to index jj has m−j+1m - j + 1 jumps, and all of them in (1−h,1](1 - h, 1] has probability e−1hm−j+1/(m−j+1)!e^{-1} h^{m-j+1}/(m-j+1)!. A step from index mm to index 1 can do both: all mm jumps in (1−h,h](1 - h, h], with probability e−1max⁡(0,2h−1)m/m!e^{-1} \max(0, 2h - 1)^m / m!. By inclusion and exclusion, e−1Hije^{-1} H_{ij} after line L6 is the probability of the step from ii to jj with VV in the band for the whole step.

The process has independent increments, so given the values at integer times the steps are independent. The path starts at V(0)=0V(0) = 0, index kk, and the event N(n)=nN(n) = n means V(n)=0V(n) = 0, index kk. So P(E,N(n)=n)=e−n(Hn)kkP(E, N(n) = n) = e^{-n} (H^n)_{kk}. Divide by P(N(n)=n)=e−nnn/n!P(N(n) = n) = e^{-n} n^n / n!. □\square

The argument above takes h<1h < 1, so that all mm values are inside the band. For h=1h = 1, c=k−1c = k - 1 and the values ±(k−1)\pm(k-1), the indices 1 and mm, are outside it. For values inside, the same computation shows that no exit happens strictly inside a step: an upper exit needs τ≤0\tau \le 0, and a lower exit from v≥−(k−2)v \ge -(k-2) needs τ≥1\tau \ge 1. Line L6 with h=1h = 1 makes column 1 and row mm zero, so no path of positive weight enters index 1, and a path that enters index mm cannot leave it. The path must end at index kk, and 1<k<m1 < k < m because k≥2k \ge 2 when d>0d > 0, so these paths get weight 0. The formula therefore needs no special case.

Claim 5 (the one-sided sum). For 0<d≤10 < d \le 1, P(D−≥d)=d∑j=0⌊n(1−d)⌋(nj)(1−d−j/n)n−j(d+j/n)j−1P(D^- \ge d) = d \sum_{j=0}^{\lfloor n(1-d) \rfloor} \binom{n}{j} (1 - d - j/n)^{n-j} (d + j/n)^{j-1}, and D+D^+ has the same law.

Proof. Let aj=d+j/na_j = d + j/n and g(j)=N(aj)−jg(j) = N(a_j) - j, where N(a)N(a) is now the number of the nn uniforms below aa. D−≥dD^- \ge d means U(j+1)≥ajU_{(j+1)} \ge a_j for some j≤n−1j \le n - 1, that is g(j)≤0g(j) \le 0 for some jj with aj≤1a_j \le 1. g(0)≥0g(0) \ge 0, and gg falls by at most 1 from jj to j+1j + 1, so the first jj with g(j)≤0g(j) \le 0 has g(j)=0g(j) = 0. The events "the first such jj" are disjoint. For a fixed jj, the event is N(aj)=jN(a_j) = j, of probability (nj)ajj(1−aj)n−j\binom{n}{j} a_j^j (1 - a_j)^{n-j}, together with g(i)>0g(i) > 0 for i<ji < j. Given N(aj)=jN(a_j) = j, the jj points below aja_j are independent and uniform on (0,aj)(0, a_j). Measure from the right end: with M(s)M(s) the number of these points in [aj−s,aj)[a_j - s, a_j), the condition g(i)>0g(i) > 0 for all i<ji < j is M(l/n)<lM(l/n) < l for l=1,…,jl = 1, \ldots, j, and this is the same as M(s)<nsM(s) < ns for all s∈(0,aj]s \in (0, a_j], because MM is a nondecreasing step function and ns>jns > j for s>j/ns > j/n. By the continuous form of the ballot theorem (Takacs), this has probability 1−j/(naj)=d/aj1 - j/(n a_j) = d / a_j. Multiply and add over jj. Claim 2 gives the same law for D+D^+. □\square

Claim 6 (the doubled tail). P(D≥d)≤2P(D+≥d)P(D \ge d) \le 2 P(D^+ \ge d) for every dd, with equality for d≥1/2d \ge 1/2.

Proof. {D≥d}={D+≥d}∪{D−≥d}\{D \ge d\} = \{D^+ \ge d\} \cup \{D^- \ge d\}, and the two events have the same probability by Claim 2. Suppose both happen, with i/n−U(i)≥di/n - U_{(i)} \ge d and U(j)−(j−1)/n≥dU_{(j)} - (j-1)/n \ge d. If j≤ij \le i, then U(j)≤U(i)U_{(j)} \le U_{(i)} gives 2d≤(i−j+1)/n≤12d \le (i - j + 1)/n \le 1. If j>ij > i, then U(i)≥0U_{(i)} \ge 0 and U(j)≤1U_{(j)} \le 1 give i/n≥di/n \ge d and 1−(j−1)/n≥d1 - (j - 1)/n \ge d, so 2d≤1−(j−1−i)/n≤12d \le 1 - (j - 1 - i)/n \le 1. So for d>1/2d > 1/2 the events are disjoint. At d=1/2d = 1/2 both cases need equalities between continuous random variables or with 0 or 1, which have probability 0. □\square

Claim 7 (validity). Each p-value returned is P(T≥tobs)P(T \ge t_{obs}) for the statistic TT, or an upper bound of it, so PH0(p≤α)≤αP_{H_0}(p \le \alpha) \le \alpha.

Proof. Line L8 returns 1−P(D<d)=P(D≥d)1 - P(D < d) = P(D \ge d) by Claim 4, and line L3 returns 2P(D+≥d)2 P(D^+ \ge d) by Claim 5, which is P(D≥d)P(D \ge d) or an upper bound by Claim 6. For any statistic TT with tail function G(t)=P(T≥t)G(t) = P(T \ge t), P(G(T)≤α)≤αP(G(T) \le \alpha) \le \alpha: let t∗=inf⁡{t:G(t)≤α}t^* = \inf\{t : G(t) \le \alpha\}; the event G(T)≤αG(T) \le \alpha is T≥t∗T \ge t^* or T>t∗T > t^*, and both have probability at most α\alpha by the right-continuity of t↦P(T>t)t \mapsto P(T > t) and the monotonicity of GG. A larger p-value only shrinks the rejection event. □\square

Discrete models. If F0F_0 has jumps, write Xi=F0−1(Ui)X_i = F_0^{-1}(U_i) with the generalized inverse. Then Fn(t)−F0(t)=Gn(F0(t))−F0(t)F_n(t) - F_0(t) = G_n(F_0(t)) - F_0(t), where GnG_n is the empirical distribution function of the UiU_i, so DD is a sup over a subset of the points used for the uniforms, and it is at most the uniform statistic. The p-values computed as for a continuous model are therefore conservative.

Two samples. Without ties, under H0H_0 the pooled sample is exchangeable, so each of the (m+nm)\binom{m+n}{m} assignments of the labels to the sorted pooled values is equally likely. Each assignment is a lattice path from (0,0)(0, 0) to (m,n)(m, n) with a step in the first coordinate for each value of the first sample. At the point (i,j)(i, j), Fm−Gn=(in−jm)/(mn)F_m - G_n = (in - jm)/(mn), and without ties these points are all the points where the two functions change. So Dm,n<t/(mn)D_{m,n} < t/(mn) exactly when the path keeps ∣in−jm∣<t\lvert in - jm \rvert < t, and the dynamic program counts these paths by adding the counts from the left and from below. The p-value is P(Dm,n≥t/(mn))P(D_{m,n} \ge t/(mn)). With ties, break them at random: the statistic with ties is a max over a subset of the points of the path after the tie break, so it is at most the statistic of that path, and the p-value is conservative.

The limit law. The asymptotic p-values use Kolmogorov's limit P(nDn>λ)→2∑k≥1(−1)k−1e−2k2λ2P(\sqrt{n} D_n > \lambda) \to 2 \sum_{k \ge 1} (-1)^{k-1} e^{-2k^2\lambda^2}, which we cite and do not prove here. For λ<1\lambda < 1 the code uses the equal form 1−2πλ∑k≥1e−(2k−1)2π2/(8λ2)1 - \frac{\sqrt{2\pi}}{\lambda} \sum_{k \ge 1} e^{-(2k-1)^2 \pi^2 / (8\lambda^2)}, from the Jacobi theta-function identity, because the alternating series converges slowly there.

Complexity

Line L1 sorts in O(nlog⁡n)O(n \log n) and line L2 is linear. The sum in line L3 has at most n+1n + 1 terms. In the matrix branch, m=2⌊nD⌋+1≤2n+1m = 2\lfloor nD \rfloor + 1 \le 2n + 1, each product of m×mm \times m matrices takes Θ(m3)\Theta(m^3) operations, and repeated squaring takes O(log⁡n)O(\log n) products. So the worst case is Θ(n3log⁡n)\Theta(n^3 \log n) time and Θ(n2)\Theta(n^2) space, and in general Θ((nD)3log⁡n)\Theta((nD)^3 \log n). When line L3 returns, the cost is Θ(nlog⁡n)\Theta(n \log n). Under H0H_0, DD is of order 1/n1/\sqrt{n}, so typical inputs have mm of order n\sqrt{n} and cost O(n3/2log⁡n)O(n^{3/2} \log n). In the Python code the matrix branch took 0.0110.011 s of CPU time at n=100n = 100, d=0.134d = 0.134. The two-sample statistic takes O((m+n)log⁡(m+n))O((m + n) \log(m + n)), and the path count takes Θ(mn)\Theta(mn) additions of integers of at most m+nm + n bits.

Properties

  • Distribution-free. For continuous F0F_0 the null law of DD depends only on nn.
  • Invariant. DD does not change under any increasing transformation applied to both the data and the model.
  • Confidence band. The exact critical value cαc_\alpha gives the band Fn(t)±cαF_n(t) \pm c_\alpha, which holds the whole of FF with probability at least 1−α1 - \alpha. The DKW inequality gives the simpler and slightly wider band Fn(t)±ln⁡(2/α)/(2n)F_n(t) \pm \sqrt{\ln(2/\alpha)/(2n)}.
  • Parameters must be fixed in advance. If the parameters of F0F_0 are estimated from the same data, the model follows the data, DD becomes smaller, and the null law changes. In a Monte Carlo run with normal data, n=20n = 20, r=2000r = 2000 samples and seed 61, the test with the estimated mean and standard deviation and the standard p-value rejected none of the 2000 samples at the nominal 5%5\%. The Lilliefors test uses the correct null law for this case.
  • Discrete models. If F0F_0 has jumps, DD is at most the statistic of the underlying uniforms, so the standard p-values are conservative.
  • Monte Carlo size. With uniform data, n=10n = 10, r=4000r = 4000 samples and seed 64, the exact test rejected 4.325%4.325\% of samples at α=0.05\alpha = 0.05.

Variants and improvements

  • One-sided tests. D+D^+ and D−D^- with the finite sum, or with the limit e−2nd2e^{-2n d^2} for large nn.
  • Two-sample test. The lattice-path count gives the exact p-value without ties. With ties, the statistic is evaluated only at the ends of tie blocks, which can only lower it, so the same p-value is conservative.
  • Estimated parameters. The Lilliefors test (Lilliefors 1967) keeps DD but takes its null law from a simulation with the parameters estimated in each simulated sample. A parametric bootstrap does the same for any model.
  • Weighted distances. The Anderson-Darling test integrates the squared difference with a weight that grows in the tails, and so has more power against differences in the tails. The Cramer-von Mises test uses the unweighted integral.
  • Normality. For the composite hypothesis of normality the Shapiro-Wilk test usually has more power.
  • Binned data. The chi-squared goodness-of-fit test works with counts in classes and allows estimated parameters with a change of the degrees of freedom.

When to use it

Use it to test a fully specified continuous model, or to compare two samples against any kind of difference, when a single number with an exact p-value is wanted. It is a good first check with a direct picture: the gap between the two curves. For a location shift between two samples the Mann-Whitney test has more power, and for differences in the tails the Anderson-Darling test does. Pair it with a Q-Q plot to see where the data and the model differ.

Pitfalls

  • Estimating the parameters from the same data. The standard p-values are then much too large; in the run above the test never rejected at 5%5\%.
  • Using the limit for small nn. At n=10n = 10, d=0.41d = 0.41 the limit gave 0.06930.0693 against the exact 0.04930.0493.
  • Discrete data. Ties and jumps in F0F_0 make the standard p-values conservative, and sometimes very much so.
  • Low power in the tails. A model that is wrong only in the tails is often accepted. With n=20n = 20 the test detected a 50% larger standard deviation in only 17.5%17.5\% of samples.
  • Cancellation. Computing a small two-sided tail as 1−P(D<d)1 - P(D < d) loses digits. Use the one-sided sum there, as line L3 does.
  • Conventions. Some programs call the alternative "greater" when F>F0F > F_0, which means the data tend to be smaller than the model. Check which sign the program uses.

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.

ks_core.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kolmogorov-smirnov-test/. The authors are listed in prov/DWDQWW.jsonl.

import math
from typing import Callable

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

# Below this two-sided tail the code returns 2 P(D+ >= d), an upper bound whose
# relative excess P(D+ >= d and D- >= d) / P(D >= d) is negligible there, instead of
# 1 - P(D < d), which loses digits to cancellation.
SMALL_TAIL = 1e-3


def ks_statistic(x: list[float], cdf: Callable[[float], float]) -> tuple[float, float, float]:
    """Return (D, D+, D-) with D+ = sup (F_n - F_0) and D- = sup (F_0 - F_n)."""
    n = len(x)
    u = [cdf(v) for v in sorted(x)]  # @line L1
    d_plus = max(i / n - ui for i, ui in enumerate(u, start=1))  # @line L2
    d_minus = max(ui - (i - 1) / n for i, ui in enumerate(u, start=1))
    return max(d_plus, d_minus), d_plus, d_minus


def smirnov_sf(n: int, d: float) -> float:
    """P(D_n^+ >= d) for a continuous F_0, by the exact finite sum of Smirnov,
    Birnbaum and Tingey: d sum_{j=0}^{floor(n(1-d))} C(n, j) (1 - d - j/n)^(n-j) (d + j/n)^(j-1).
    Every term is positive, so the sum does not cancel; each term is formed in logs."""
    if d <= 0.0:
        return 1.0
    if d >= 1.0:
        return 0.0
    terms = []
    for j in range(int(math.floor(n * (1.0 - d) + 1e-12)) + 1):
        a = 1.0 - d - j / n
        if a <= 0.0:
            if n - j > 0:
                continue
            log_a = 0.0  # 0^0 = 1
        else:
            log_a = (n - j) * math.log(a)
        log_c = math.lgamma(n + 1) - math.lgamma(j + 1) - math.lgamma(n - j + 1)
        terms.append(math.exp(log_c + log_a + (j - 1) * math.log(d + j / n)))
    return min(1.0, d * math.fsum(terms))


def _matmul(a: list[list[float]], b: list[list[float]]) -> list[list[float]]:
    bt = list(zip(*b))
    return [[math.fsum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def kolmogorov_cdf(n: int, d: float) -> float:
    """P(D_n < d) for a continuous F_0, by the matrix method of Durbin (1973) in the
    form of Marsaglia, Tsang and Wang (2003). Powers are rescaled by powers of 2."""
    if d <= 0.0:
        return 0.0
    if d >= 1.0:
        return 1.0
    nd = n * d
    k = int(math.floor(nd)) + 1  # @line L4
    h = k - nd
    m = 2 * k - 1
    fact = [math.factorial(i) for i in range(m + 1)]
    hm = [[1.0 / fact[i - j + 1] if i - j + 1 >= 0 else 0.0 for j in range(m)]
          for i in range(m)]  # @line L5
    for i in range(m):  # @line L6
        hm[i][0] -= h ** (i + 1) / fact[i + 1]
        hm[m - 1][i] -= h ** (m - i) / fact[m - i]
    hm[m - 1][0] += max(0.0, 2.0 * h - 1.0) ** m / fact[m]
    # Repeated squaring; each matrix carries a binary exponent so nothing overflows.
    result, result_exp = None, 0
    base, base_exp = hm, 0
    e = n
    while e:  # @line L7
        if e & 1:
            if result is None:
                result, result_exp = base, base_exp
            else:
                result, result_exp = _matmul(result, base), result_exp + base_exp
                big = max(abs(v) for row in result for v in row)
                if big > 0.0:
                    shift = math.frexp(big)[1]
                    result = [[math.ldexp(v, -shift) for v in row] for row in result]
                    result_exp += shift
        e >>= 1
        if e:
            base, base_exp = _matmul(base, base), 2 * base_exp
            big = max(abs(v) for row in base for v in row)
            if big > 0.0:
                shift = math.frexp(big)[1]
                base = [[math.ldexp(v, -shift) for v in row] for row in base]
                base_exp += shift
    t = result[k - 1][k - 1]
    if t <= 0.0:
        return 0.0
    log_p = math.log(t) + result_exp * math.log(2.0) + math.lgamma(n + 1) - n * math.log(n)
    return min(1.0, math.exp(log_p))


def kolmogorov_sf(x: float) -> float:
    """The limit P(K > x) = 2 sum_{k>=1} (-1)^(k-1) exp(-2 k^2 x^2) of sqrt(n) D_n.
    For x < 1 the alternating series converges slowly, so the code uses the
    equivalent form 1 - (sqrt(2 pi)/x) sum_{k>=1} exp(-(2k-1)^2 pi^2 / (8 x^2))."""
    if x <= 0.0:
        return 1.0
    if x < 1.0:
        s = math.fsum(math.exp(-((2 * k - 1) ** 2) * math.pi**2 / (8 * x * x)) for k in range(1, 30))
        return max(0.0, 1.0 - math.sqrt(2 * math.pi) / x * s)
    return min(1.0, 2.0 * math.fsum((-1) ** (k - 1) * math.exp(-2.0 * k * k * x * x)
                                    for k in range(1, 101)))


def ks_1samp(
    x: list[float],
    cdf: Callable[[float], float],
    alternative: str = "two-sided",
    method: str = "auto",
) -> tuple[float, float]:
    """One-sample Kolmogorov-Smirnov test of H0: the data have the continuous CDF F_0.

    Returns (statistic, p). "greater" uses D+ (H1: F > F_0 somewhere), "less"
    uses D- (H1: F < F_0 somewhere); their exact null laws are the same.
    method "exact" uses the exact finite-n law, "asymptotic" the Kolmogorov
    limit (or exp(-2 n d^2) for one side), and "auto" is exact for n <= 100.
    """
    if alternative not in ALTERNATIVES:
        raise ValueError("unknown alternative")
    if method not in ("auto", "exact", "asymptotic"):
        raise ValueError("unknown method")
    n = len(x)
    if n == 0:
        raise ValueError("need at least one observation")
    d, d_plus, d_minus = ks_statistic(x, cdf)
    use_exact = method == "exact" or (method == "auto" and n <= 100)
    if alternative != "two-sided":
        s = d_plus if alternative == "greater" else d_minus
        if use_exact:
            return s, smirnov_sf(n, s)
        return s, min(1.0, math.exp(-2.0 * n * s * s))
    if not use_exact:
        return d, kolmogorov_sf(math.sqrt(n) * d)
    tail2 = 2.0 * smirnov_sf(n, d)
    if d >= 0.5 or tail2 < SMALL_TAIL:  # @line L3
        return d, min(1.0, tail2)
    return d, max(0.0, 1.0 - kolmogorov_cdf(n, d))  # @line L8


def ks_2samp_stat(x: list[float], y: list[float]) -> tuple[int, int, int]:
    """Return (t, m, n) with D = t / (m n) = sup |F_m - G_n|, where t = max |i n - j m|
    over the points after each block of equal values in the merged order."""
    m, n = len(x), len(y)
    xs, ys = sorted(x), sorted(y)
    i = j = t = 0
    while i < m or j < n:
        v = min(xs[i] if i < m else math.inf, ys[j] if j < n else math.inf)
        while i < m and xs[i] == v:
            i += 1
        while j < n and ys[j] == v:
            j += 1
        t = max(t, abs(i * n - j * m))
    return t, m, n


def ks_2samp(x: list[float], y: list[float], method: str = "exact") -> tuple[float, float]:
    """Two-sample Kolmogorov-Smirnov test, two-sided. Returns (D, p).

    method "exact" counts the lattice paths from (0, 0) to (m, n) that stay
    strictly inside |i n - j m| < t; the p-value is 1 minus their share of all
    C(m + n, m) paths, in exact integers. It is exact when there are no ties.
    method "asymptotic" uses the Kolmogorov limit at sqrt(m n / (m + n)) D.
    """
    if not x or not y:
        raise ValueError("both samples must be nonempty")
    t, m, n = ks_2samp_stat(x, y)
    d = t / (m * n)
    if method == "asymptotic":
        return d, kolmogorov_sf(math.sqrt(m * n / (m + n)) * d)
    if method != "exact":
        raise ValueError("unknown method")
    row = [0] * (n + 1)
    for i in range(m + 1):
        for j in range(n + 1):
            if abs(i * n - j * m) >= t:
                row[j] = 0
            elif i == 0 and j == 0:
                row[j] = 1
            else:
                row[j] = (row[j] if i > 0 else 0) + (row[j - 1] if j > 0 else 0)
    total = math.comb(m + n, m)
    return d, (total - row[n]) / total
kolmogorov_smirnov_test.py 12 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kolmogorov-smirnov-test/. The authors are listed in prov/DWDQWW.jsonl.
"""Entry point named after the slug. The code lives in ks_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""

from ks_core import (
    ALTERNATIVES, SMALL_TAIL, kolmogorov_cdf, kolmogorov_sf, ks_1samp, ks_2samp, ks_2samp_stat,
    ks_statistic, smirnov_sf,
)

__all__ = ["ALTERNATIVES", "SMALL_TAIL", "kolmogorov_cdf", "kolmogorov_sf", "ks_1samp",
           "ks_2samp", "ks_2samp_stat", "ks_statistic", "smirnov_sf"]
test_kolmogorov_smirnov_test.py 165 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kolmogorov-smirnov-test/. The authors are listed in prov/DWDQWW.jsonl.

import itertools
import math
import random
from fractions import Fraction

import pytest

from kolmogorov_smirnov_test import (
    kolmogorov_cdf, kolmogorov_sf, ks_1samp, ks_2samp, ks_2samp_stat, ks_statistic, smirnov_sf,
)

X = [0.42, 0.06, 1.95, 0.88, 0.13, 3.10, 0.27, 0.71, 0.09, 0.35]


def exp_cdf(v: float) -> float:
    return 1.0 - math.exp(-v) if v > 0 else 0.0


def box_probability(lo: list[Fraction], hi: list[Fraction]) -> Fraction:
    """P(lo_i < U_(i) < hi_i for all i) for the order statistics of n uniforms, exactly.

    The density of the order statistics is n! on 0 < u_1 < ... < u_n < 1. Integrate
    u_1, then u_2, ... as piecewise polynomials in exact Fractions."""
    n = len(lo)
    pts = sorted(set([Fraction(0), Fraction(1)] + lo + hi))
    pieces = len(pts) - 1

    def value(p: list[Fraction], u: Fraction) -> Fraction:
        return sum(c * u**i for i, c in enumerate(p))

    def inside(i: int, t: int) -> bool:
        return lo[i] <= pts[t] and pts[t + 1] <= hi[i]

    f = [[Fraction(1)] if inside(0, t) else [Fraction(0)] for t in range(pieces)]
    for i in range(1, n + 1):
        g, acc = [], Fraction(0)
        for t in range(pieces):  # g(u) = integral of f from 0 to u
            p = [Fraction(0)] + [c / (j + 1) for j, c in enumerate(f[t])]
            p[0] += acc - value(p, pts[t])
            g.append(p)
            acc = value(p, pts[t + 1])
        if i == n:
            return acc * math.factorial(n)
        f = [g[t] if inside(i, t) else [Fraction(0)] for t in range(pieces)]
    return Fraction(1)


def exact_two_sided(n: int, d: Fraction) -> Fraction:
    """P(D_n < d): i/n - d < U_(i) < (i - 1)/n + d for every i."""
    lo = [max(Fraction(0), Fraction(i, n) - d) for i in range(1, n + 1)]
    hi = [min(Fraction(1), Fraction(i - 1, n) + d) for i in range(1, n + 1)]
    return box_probability(lo, hi)


def exact_one_sided(n: int, d: Fraction) -> Fraction:
    """P(D_n^+ < d): U_(i) > i/n - d for every i."""
    lo = [max(Fraction(0), Fraction(i, n) - d) for i in range(1, n + 1)]
    return box_probability(lo, [Fraction(1)] * n)


def test_page_example() -> None:
    d, d_plus, d_minus = ks_statistic(X, exp_cdf)
    assert (round(d, 4), round(d_plus, 4), round(d_minus, 4)) == (0.2570, 0.2570, 0.0582)
    assert ks_1samp(X, exp_cdf)[1] == pytest.approx(0.44931051, abs=1e-7)
    assert ks_1samp(X, exp_cdf, method="asymptotic")[1] == pytest.approx(0.52337859, abs=1e-7)
    assert ks_1samp(X, exp_cdf, "greater")[1] == pytest.approx(0.22668362, abs=1e-7)
    a = [1.2, 3.4, 2.2, 5.1, 4.4, 3.9]
    b = [0.3, 1.1, 2.0, 0.9, 1.7, 2.5, 0.5]
    assert ks_2samp_stat(a, b) == (29, 6, 7)
    assert ks_2samp(a, b)[1] == pytest.approx(116 / 1716, rel=1e-12)


def test_matrix_method_against_exact_integration() -> None:
    for n in range(1, 8):
        for d in (Fraction(1, 9), Fraction(1, 5), Fraction(2, 7), Fraction(3, 10), Fraction(1, 2),
                  Fraction(3, 5), Fraction(5, 7), Fraction(9, 10)):
            want = float(exact_two_sided(n, d))
            assert kolmogorov_cdf(n, float(d)) == pytest.approx(want, rel=1e-11, abs=1e-14)


def test_one_observation() -> None:
    # D_1 = max(u, 1 - u), so P(D_1 < d) = 2d - 1 for 1/2 <= d <= 1.
    for d in (0.55, 0.7, 0.95):
        assert kolmogorov_cdf(1, d) == pytest.approx(2 * d - 1, rel=1e-12)
    assert kolmogorov_cdf(1, 0.4) == 0.0


def test_one_sided_sum_against_exact_integration() -> None:
    for n in range(1, 8):
        for d in (Fraction(1, 9), Fraction(1, 4), Fraction(2, 5), Fraction(3, 5), Fraction(4, 5)):
            assert smirnov_sf(n, float(d)) == pytest.approx(float(1 - exact_one_sided(n, d)), rel=1e-11)


def test_two_sided_is_twice_one_sided_above_half() -> None:
    # For d >= 1/2 the events D+ >= d and D- >= d cannot both happen.
    for n in range(1, 8):
        for d in (Fraction(1, 2), Fraction(3, 5), Fraction(4, 5)):
            assert 1 - exact_two_sided(n, d) == 2 * (1 - exact_one_sided(n, d))


def test_statistic_against_direct_supremum() -> None:
    rng = random.Random(1)
    for _ in range(200):
        x = [rng.random() for _ in range(rng.randint(1, 12))]
        n = len(x)
        best_plus = best_minus = 0.0
        for t in x:  # the supremum is attained at a data point or just before it
            at = sum(v <= t for v in x) / n
            before = sum(v < t for v in x) / n
            best_plus = max(best_plus, at - t)
            best_minus = max(best_minus, t - before)
        d, d_plus, d_minus = ks_statistic(x, lambda v: v)
        assert d_plus == pytest.approx(best_plus, abs=1e-15)
        assert d_minus == pytest.approx(best_minus, abs=1e-15)
        assert d == max(d_plus, d_minus)


def test_two_sample_against_all_labelings() -> None:
    rng = random.Random(2)
    for _ in range(40):
        m, n = rng.randint(1, 6), rng.randint(1, 6)
        pooled = rng.sample(range(100), m + n)  # distinct values
        x, y = pooled[:m], pooled[m:]

        def dist(a: list[int], b: list[int]) -> Fraction:
            return max(abs(Fraction(sum(v <= t for v in a), len(a)) - Fraction(sum(v <= t for v in b), len(b)))
                       for t in a + b)

        observed = dist(x, y)
        assert Fraction(ks_2samp(x, y)[0]).limit_denominator(1000) == observed
        hits = total = 0
        for idx in itertools.combinations(range(m + n), m):
            a = [pooled[i] for i in idx]
            b = [pooled[i] for i in range(m + n) if i not in idx]
            total += 1
            hits += dist(a, b) >= observed
        assert ks_2samp(x, y)[1] == pytest.approx(hits / total, rel=1e-12)


def test_limit_law() -> None:
    assert kolmogorov_sf(1.3580986393) == pytest.approx(0.05, abs=1e-9)
    # The two series used below and above x = 1 agree.
    left = 1.0 - math.sqrt(2 * math.pi) * sum(math.exp(-((2 * k - 1) ** 2) * math.pi**2 / 8) for k in range(1, 30))
    assert kolmogorov_sf(1.0) == pytest.approx(left, abs=1e-14)
    assert kolmogorov_cdf(400, 1.2 / 20) == pytest.approx(1 - kolmogorov_sf(1.2), abs=1e-2)


def test_size_monte_carlo() -> None:
    rng = random.Random(64)
    r, alpha = 1500, 0.05
    hits = sum(ks_1samp([rng.random() for _ in range(10)], lambda v: v)[1] <= alpha for _ in range(r))
    assert hits / r <= alpha + 4 * math.sqrt(alpha * (1 - alpha) / r)


def test_edges() -> None:
    with pytest.raises(ValueError):
        ks_1samp([], exp_cdf)
    with pytest.raises(ValueError):
        ks_1samp([1.0], exp_cdf, "both")
    with pytest.raises(ValueError):
        ks_2samp([], [1.0])
    assert ks_2samp([1.0, 2.0], [1.0, 2.0])[0] == 0.0

History

Andrey Kolmogorov (1933) defined DnD_n for a continuous distribution function, showed that its law does not depend on FF, and found the limit law of nDn\sqrt{n} D_n. In the same volume of the same journal, Glivenko proved that Dn→0D_n \to 0 for continuous FF, and Cantelli extended this to every FF. Nikolai Smirnov studied the one-sided statistics and the two-sample statistic, and published tables of the limit laws in 1948. The finite sum for the one-sided law is due to Smirnov and to Birnbaum and Tingey (1951). Durbin wrote the exact two-sided law as a matrix power, and Marsaglia, Tsang and Wang (2003) turned it into a fast and accurate program. Lilliefors (1967) showed by simulation that estimating the parameters of a normal model changes the null law, and gave a corrected table.

References

  1. A. N. Kolmogorov, Sulla determinazione empirica di una legge di distribuzione, Giornale dell'Istituto Italiano degli Attuari 4, 1933, pages 83 to 91, the statistic D_n for a continuous distribution function, the fact that its law does not depend on F, and the limit law of sqrt(n) D_n
  2. N. Smirnov, Table for estimating the goodness of fit of empirical distributions, Annals of Mathematical Statistics 19(2), 1948, pp. 279 to 281 (the table of the limit law and its use for one and two samples)
  3. George Marsaglia, Wai Wan Tsang and Jingbo Wang, Evaluating Kolmogorov's distribution, Journal of Statistical Software 8(18), 2003, the matrix H, the corrections with h, and the exact P(D_n < d) as (n!/n^n) times an entry of H^n, computed by squaring with rescaling
  4. Hubert W. Lilliefors, On the Kolmogorov-Smirnov test for normality with mean and variance unknown, Journal of the American Statistical Association 62(318), 1967, pp. 399 to 402 (the Monte Carlo table for the statistic with estimated parameters)

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