I've been reading the Wikipedia articles about various statistical tests, and trying to code up programs that perform them. However, the article on the Kolmogorov-Smirnov test is rather unclear to me. Can somebody explain, in simple language, how I would write a program that takes a list of real numbers and a CDF, and computes a p-value for how closely they match?
|
|
Here is an answer to a related question that as part of the answer gives an example of computing the statistic and a graph demonstrating the general idea. |
|||
|
|
|||
We're looking for long answers that provide some explanation and context. Don't just give a one-line answer: please explain why you're recommending it as a solution. Answers that don't explain anything will be deleted. See Good Subjective, Bad Subjective for more information. |
|||
|
I can't make any sense of the code that ttnphns posted. But the linked algorithms document has helped. First, it appears that if you take your $n$ samples and sort them into ascending order, then the emperical cumulative distribution function can be defined as $$ \hat{F}(x) = \left\{ \begin{array}{ll} 0 & \text{if } x < x_0 \\ i/n & \text{if } x_i \leq x < x_{i+1} \\ 1 & \text{if } x_n < x \\ \end{array} \right. $$ (Assuming that the $x_i$ are your samples in ascending order.) It now remains only to discover the maximum distance between $\hat{F}(x)$ and your target CDF $F(x)$. It appears that finding the minimum distance would be quite hard, since it could be located anywhere in a given span. (The CDF might cross the EDF at any point.) However, since a CDF is, by definition, monotonically increasing, it follows that the maximum distance has to be at one end or the other of each span. Edit: Corrected formulas. (Oops!) So, it seems the complete algorithm is this:
To get a p-value, you need to compare the statistic against the CDF of the Kolgomorov distribution. Apparently this involves the elliptic theta function or something... o_O PS. It seems to not matter whether you choose $d_H = |i/n - F(x_{i-1})|$ or $d_H = |(i-1)/n - F(x_i)|$. Both do essentially the same thing. |
|||||||||||||||
|
|
Below I've written for you SPSS code of one-sample K-S test following SPSS algorithms document. In my example, an observed variable X is tested against uniform theoretical distribution. Despite that the snippet is not pseudocode you will understand easily what it is doing if you compare the comments with the document.
|
|||||||||||||
|
|
Purely for giggles, here is an implementation of the KS test in Haskell:
Argue among yourselves whether this is any more readable... |
|||
|
|