# Kolmogorov–Smirnov测试

p的公式很复杂, 但是代码很易懂,这里上下代码:

```//x和y是两组抽样结果, 通过这个函数, 返回p值, 这个函数可以判断这两个结构是不是来自于同一个抽样函数
public double kolmogorovSmirnovStatistic(double[] x, double[] y) {
this.checkArray(x);
this.checkArray(y);
double[] sx = MathArrays.copyOf(x);
double[] sy = MathArrays.copyOf(y);
Arrays.sort(sx);//排序
Arrays.sort(sy);
int n = sx.length;
int m = sy.length;
double supD = 0.0D;//初始化结果

int i;
double cdf_y;
int xIndex;
double cdf_x;
double curD;
for(i = 0; i < n; ++i) {//遍历x, 然后找x在y中的位置
cdf_y = ((double)i + 1.0D) / (double)n;
xIndex = Arrays.binarySearch(sy, sx[i]);
cdf_x = xIndex >= 0?((double)xIndex + 1.0D) / (double)m:((double)(-xIndex) - 1.0D) / (double)m;//位置
curD = FastMath.abs(cdf_y - cdf_x);
if(curD > supD) {//取最大
supD = curD;
}
}

for(i = 0; i < m; ++i) {//遍历y, 找y在x中的位置
cdf_y = ((double)i + 1.0D) / (double)m;
xIndex = Arrays.binarySearch(sx, sy[i]);
cdf_x = xIndex >= 0?((double)xIndex + 1.0D) / (double)n:((double)(-xIndex) - 1.0D) / (double)n;
curD = FastMath.abs(cdf_x - cdf_y);
if(curD > supD) {
supD = curD;
}
}

return supD;
}```

```//m和n是样本集合的大小
private double getDValue(int m, int n) {
Preconditions.checkArgument(m > 0, "input sample size should be positive.");
Preconditions.checkArgument(n > 0, "input sample size should be positive.");
double first = (double) m;
double second = (double) n;
return 1.63 * Math.sqrt((first + second) / (first * second));
}```

https://www.webdepot.umontreal.ca/Usagers/angers/MonDepotPublic/STT3500H10/Critical_KS.pdf