in commons-statistics-inference/src/main/java/org/apache/commons/statistics/inference/ChiSquareTest.java [155:191]
public double statistic(long[][] counts) {
Arguments.checkCategoriesRequiredSize(counts.length, 2);
Arguments.checkValuesRequiredSize(counts[0].length, 2);
Arguments.checkRectangular(counts);
Arguments.checkNonNegative(counts);
final int nRows = counts.length;
final int nCols = counts[0].length;
// compute row, column and total sums
final double[] rowSum = new double[nRows];
final double[] colSum = new double[nCols];
double sum = 0;
for (int row = 0; row < nRows; row++) {
for (int col = 0; col < nCols; col++) {
rowSum[row] += counts[row][col];
colSum[col] += counts[row][col];
}
checkNonZero(rowSum[row], ROW, row);
sum += rowSum[row];
}
for (int col = 0; col < nCols; col++) {
checkNonZero(colSum[col], COLUMN, col);
}
// Compute expected counts and chi-square
double chi2 = 0;
for (int row = 0; row < nRows; row++) {
for (int col = 0; col < nCols; col++) {
final double e = (rowSum[row] * colSum[col]) / sum;
final double d = counts[row][col] - e;
chi2 += d * d / e;
}
}
return chi2;
}