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
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Andrey Kolmogorov, Nikolai Smirnov, 1933
The Kolmogorov-Smirnov test checks whether a sample comes from a given continuous distribution function . Its statistic is the largest vertical distance between the empirical distribution function and . After sorting, is the largest of simple differences. Under the null hypothesis the law of is the same for every continuous , 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. are independent with an unknown distribution function . is a fully specified continuous distribution function.
Hypotheses. : . Two-sided : . One-sided "greater": for some . One-sided "less": for some .
Statistic. With for the sorted data,
and . The one-sided tests use or .
Null distribution. Exact. If is continuous, is uniform on under , and , and are functions of the only. So their laws depend on and not on . and have the same law, for . The two-sided law has no short closed form; line L8 computes it exactly. As , , the Kolmogorov distribution, and .
P-values. For an observed value the two-sided p-value is , and the one-sided p-values are and . No doubling rule is needed: is already two-sided. For the events and cannot both happen, so exactly. For every , .
Rejection rule and size. Reject at level when . For continuous the exact p-value gives size when is a value of the tail function, and at most always. The exact 5% critical values of are , , , and for . The limit gives , that is , , , and , so the limit test is conservative for small .
Sensitivity and power. The test is consistent against every fixed , because by the Glivenko-Cantelli theorem. The statistic is a sup over all , and the variance of is largest near the median of , 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 with , samples per case and , it rejected of samples from (seed 62) and of samples from (seed 63).
The algorithm
The pseudocode gives the one-sample two-sided test. Here is the finite sum for above, and indices of the matrix run from 1.
KOLMOGOROV-SMIRNOV(x_1, ..., x_n, F_0)- 1
sort x; u_i ← F_0(x_(i)) for i = 1, ..., n - 2
D+ ← max_i (i/n - u_i); D- ← max_i (u_i - (i - 1)/n); D ← max(D+, D-) - 3
if D ≥ 1/2 or 2 · SMIRNOV(n, D) < 10^-3 then return D, min(1, 2 · SMIRNOV(n, D)) - 4
k ← ⌊nD⌋ + 1; h ← k - nD; m ← 2k - 1 - 5
H[i][j] ← 1/(i - j + 1)! if i - j + 1 ≥ 0, else 0, for 1 ≤ i, j ≤ m - 6
H[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! - 7
T ← H^n by repeated squaring, rescaling every product by a power of 2 - 8
return D, 1 - (n!/n^n) · T[k][k]
Lines L1 and L2 compute the statistic: between two data points is constant and 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 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 at , and at , . Line L3 avoids there, because that subtraction loses the digits of a small tail: the float error of line L8 was at , and at , . 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 , and 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 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 .
Two samples. For samples of sizes and with distribution functions and , the statistic is . Walk through the merged sorted values; after values of the first sample and values of the second, . So with the largest at the end of each block of equal values. Under without ties, the order of the labels is uniform over the lattice paths from to . A dynamic program counts the paths that keep 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, . The data are , so . After sorting, line L1 gives
Line L2 gives at and at , so . The two-sided tail is not small, so lines L4 to L8 run with , and a matrix, and give the exact . The one-sided p-values are for "greater" and for "less", and the asymptotic two-sided p-value is . The data are compatible with the model. Against the exponential law with mean the same data give and , so the test does not separate the two models with ten points.
The exact law against the limit. For , , the exact tail is and the limit gives ; the bound gives . At , , which is above the exact 5% point, the exact tail equals to the digits shown, while the limit gives . At , the exact tail is and the limit gives .
Two samples. Take and , so , . After the value , one and six values are passed, so , the largest gap. The path count finds of the label orders with a gap of at least , so . The limit gives .
Correctness
The proof is in proofs/correctness.md. The probability integral transform makes the null law of that of uniform order statistics. Lines L1 and L2 compute the sup because is a step function and is monotone. means that every lies in the open interval . Embed the uniforms in a Poisson process: then this event is a band condition on a Markov chain observed at the steps , the band has integer states, and is 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 follows from the ballot theorem. For the two one-sided events are disjoint, and for smaller the doubled one-sided tail is an upper bound, so every p-value is exact or conservative, and the test has size at most .
Proof: The Kolmogorov-Smirnov statistic, its exact null law, and why the p-values are validfull
We use the pseudocode of the page. is continuous, , and with and , as in line L4.
Claim 1 (the statistic). Lines L1 and L2 return and .
Proof. On the function equals (or more, at tied points, which only raises the value at the last index of the tie) and is nondecreasing, so on this interval is . Before , . So . On , and by continuity, which gives . After , .
Claim 2 (distribution-free). Under , has the law of the order statistics of independent uniforms on . So the laws of , and depend only on , and and have the same law.
Proof. For continuous , for , so is uniform, and is nondecreasing, so it maps the sorted data to the sorted uniforms. By Claim 1 the statistics are functions of these values. The map keeps the joint law and turns into with , so it exchanges and .
Claim 3 (the band). if and only if for every .
Proof. This is Claim 1: means for all , and means for all .
Claim 4 (the matrix formula). with from lines L5 and L6.
Proof. Let be a Poisson process of rate 1 on with jump times . Given , the points are distributed as . By Claim 3, becomes the event that for . Let . Between jumps falls at slope 1, and at a jump it rises by 1. The condition says that stays below just after each jump, and says that stays above just before each jump. So is the event that and for all .
At integer times is an integer. Take first ; then , and allows the values . Give the value the index , so is the top value and is the bottom value . A step from time to from index to index needs exactly jumps, which has probability , or 0 if . This is times the entry of line L5.
Now remove the steps that leave the band between integer times. Suppose that reaches at a time inside the step. After it falls by at most , so the end value is at least . For an end value of at most this needs , which is not possible. So upper exits happen only in steps that end at index 1, and then only with . A step from index to index 1 has jumps. With jumps by time , reaches when , and , so all jumps must be in . That has probability . In the same way, reaches from the start value before the first jump at time when , that is . This is possible inside a step only for , the index , and then exactly when no jump falls in . After a jump, is at least . A step from index to index has jumps, and all of them in has probability . A step from index to index 1 can do both: all jumps in , with probability . By inclusion and exclusion, after line L6 is the probability of the step from to with 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 , index , and the event means , index . So . Divide by .
The argument above takes , so that all values are inside the band. For , and the values , the indices 1 and , are outside it. For values inside, the same computation shows that no exit happens strictly inside a step: an upper exit needs , and a lower exit from needs . Line L6 with makes column 1 and row zero, so no path of positive weight enters index 1, and a path that enters index cannot leave it. The path must end at index , and because when , so these paths get weight 0. The formula therefore needs no special case.
Claim 5 (the one-sided sum). For , , and has the same law.
Proof. Let and , where is now the number of the uniforms below . means for some , that is for some with . , and falls by at most 1 from to , so the first with has . The events "the first such " are disjoint. For a fixed , the event is , of probability , together with for . Given , the points below are independent and uniform on . Measure from the right end: with the number of these points in , the condition for all is for , and this is the same as for all , because is a nondecreasing step function and for . By the continuous form of the ballot theorem (Takacs), this has probability . Multiply and add over . Claim 2 gives the same law for .
Claim 6 (the doubled tail). for every , with equality for .
Proof. , and the two events have the same probability by Claim 2. Suppose both happen, with and . If , then gives . If , then and give and , so . So for the events are disjoint. At both cases need equalities between continuous random variables or with 0 or 1, which have probability 0.
Claim 7 (validity). Each p-value returned is for the statistic , or an upper bound of it, so .
Proof. Line L8 returns by Claim 4, and line L3 returns by Claim 5, which is or an upper bound by Claim 6. For any statistic with tail function , : let ; the event is or , and both have probability at most by the right-continuity of and the monotonicity of . A larger p-value only shrinks the rejection event.
Discrete models. If has jumps, write with the generalized inverse. Then , where is the empirical distribution function of the , so 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 the pooled sample is exchangeable, so each of the assignments of the labels to the sorted pooled values is equally likely. Each assignment is a lattice path from to with a step in the first coordinate for each value of the first sample. At the point , , and without ties these points are all the points where the two functions change. So exactly when the path keeps , and the dynamic program counts these paths by adding the counts from the left and from below. The p-value is . 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 , which we cite and do not prove here. For the code uses the equal form , from the Jacobi theta-function identity, because the alternating series converges slowly there.
Complexity
Line L1 sorts in and line L2 is linear. The sum in line L3 has at most terms. In the matrix branch, , each product of matrices takes operations, and repeated squaring takes products. So the worst case is time and space, and in general . When line L3 returns, the cost is . Under , is of order , so typical inputs have of order and cost . In the Python code the matrix branch took s of CPU time at , . The two-sample statistic takes , and the path count takes additions of integers of at most bits.
Properties
- Distribution-free. For continuous the null law of depends only on .
- Invariant. does not change under any increasing transformation applied to both the data and the model.
- Confidence band. The exact critical value gives the band , which holds the whole of with probability at least . The DKW inequality gives the simpler and slightly wider band .
- Parameters must be fixed in advance. If the parameters of are estimated from the same data, the model follows the data, becomes smaller, and the null law changes. In a Monte Carlo run with normal data, , 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 . The Lilliefors test uses the correct null law for this case.
- Discrete models. If has jumps, is at most the statistic of the underlying uniforms, so the standard p-values are conservative.
- Monte Carlo size. With uniform data, , samples and seed 64, the exact test rejected of samples at .
Variants and improvements
- One-sided tests. and with the finite sum, or with the limit for large .
- 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 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 .
- Using the limit for small . At , the limit gave against the exact .
- Discrete data. Ties and jumps in 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 the test detected a 50% larger standard deviation in only of samples.
- Cancellation. Computing a small two-sided tail as loses digits. Use the one-sided sum there, as line L3 does.
- Conventions. Some programs call the alternative "greater" when , 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.
# 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 for a continuous distribution function, showed that its law does not depend on , and found the limit law of . In the same volume of the same journal, Glivenko proved that for continuous , and Cantelli extended this to every . 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
- 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
- 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)
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag DWDQWW Edit this page History Report an error Markdown