public static function chiSquaredTest(array $observed, array $expected)
{
// Arrays must have the same number of elements
if (count($observed) !== count($expected)) {
throw new Exception\BadDataException('Observed and expected must have the same number of elements');
}
// Reset array indexes and initialize
$O = array_values($observed);
$E = array_values($expected);
$n = count($observed);
// number of terms
$k = $n - 1;
// degrees of freedom
$χ² = 0;
/*
* (Oᵢ - Eᵢ)²
* χ² = ∑ ----------
* Eᵢ
*/
for ($i = 0; $i < $n; $i++) {
$χ² += ($O[$i] - $E[$i]) ** 2 / $E[$i];
}
$p = ChiSquared::above($χ², $k);
return ['chi-square' => $χ², 'p' => $p];
}