Kolmogorov–Smirnov
How far is the empirical distribution of a sample from a claimed one, or from another sample's? The Kolmogorov–Smirnov statistic is the largest vertical gap between the two step functions, and its distribution under the null hypothesis can be computed exactly.
One sample
import { ksTest, normal, kolmogorovCdf } from "@ratmath/stats";
const u = ksTest([0.1, 0.2, 0.35, 0.5, 0.9], (x) => x); // against the uniform cdf F(x) = x
u.statistic; // 3/10
u.pValue; // 83/125, exact
const z = ksTest([0.61, 0.29, 0.06, 0.59, -1.73, -0.74, 0.51, -0.56, 0.39, 1.64, 0.05, -0.06, 0.64,
-0.82, 0.37, 1.77, 1.09, -1.28, 2.36, 1.31, 1.05, -0.32, -0.40, 1.06, -2.47], normal());
z.statistic; // an enclosure around 0.174092: the normal cdf is certified, not exact
z.pValue; // an enclosure around 0.389741 (certified)
With the sample sorted, , the statistic is
For a continuous , has the same law whatever is. Marsaglia, Tsang and Wang showed that for an explicit -square matrix with , whose entries are rational when is. So kolmogorovCdf(n, d) is exact: kolmogorovCdf(10, "0.274") is a fraction whose decimal expansion begins 0.6284796154565043, the value in their paper. When is certified, is an enclosure and so is the p-value, since falls as grows.
Far in the tail the matrix grows, and there a sharper route is cheaper: the one-sided statistic has the exact Smirnov–Birnbaum–Tingey tail
and . When that enclosure is what is returned (method "one-sided bound"): it is tiny and decides any usual level. Above the p-value is simulated from a seed instead.
Two samples
const k = ksTest([1, 2, 3, 4, 5, 6], [3.5, 4.5, 6.5, 7.5, 8.5, 9.5]);
k.statistic; // 2/3
k.pValue; // 1/7, exact
ksTest([1, 2, 3, 4, 5, 6], [3.5, 4.5, 6.5, 7.5, 8.5, 9.5], { alternative: "less" }).pValue; // 1/14
Under the null hypothesis every interleaving of the and values is equally likely. An interleaving is a lattice path from to , and the event says the path stays inside a band around the diagonal. Counting the paths that stay inside, by dynamic programming over the grid, gives the exact p-value. With ties the band is only checked where the pooled value changes, which gives the exact conditional distribution. One-sided alternatives use one edge of the band; "greater" means tends to be larger, so its empirical cdf lies below.
@ratmath/stats and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.