Chi-square tests
Do counts fit a model? Are two classifications independent? Pearson's statistic adds up (observed − expected)²/expected over the cells. It is an exact fraction; its p-value comes from the chi-square distribution, certified.
Goodness of fit
import { chiSquareTest } from "@ratmath/stats";
const die = chiSquareTest([22, 17, 21, 18, 12, 30]); // 120 rolls: is the die fair?
die.statistic; // 91/10
die.df; // 5
die.contributions; // [1/5, 9/20, 1/20, 1/5, 16/5, 5]: the six cells' shares
String(die); // "chi-square goodness-of-fit test: p = 0.105141 (certified, greater)"
// Mendel's peas: round yellow, round green, wrinkled yellow, wrinkled green, against 9:3:3:1
chiSquareTest([315, 108, 101, 32], { p: ["9/16", "3/16", "3/16", "1/16"] }); // X² = 196/417, p = 0.925426
With observed counts and expected counts ,
is approximately with degrees of freedom when the model is right, less one for each parameter estimated from the data (option estimated). Large values mean a poor fit, so the p-value is the upper tail. The approximation needs the expected counts to be not too small; smallExpected flags any below 5. Mendel's fit is so good that Fisher, looking at all of Mendel's experiments together, suspected the data had been tidied.
Independence
For an table, independence of the two classifications predicts from the row and column totals, and has degrees of freedom.
const t = chiSquareTest([[20, 30, 25], [30, 15, 30]]);
t.statistic; // 82/11
t.expected; // [[25, 45/2, 55/2], [25, 45/2, 55/2]]
t.df; // 2
String(t); // "… p = 0.024058 …"
const small = [[12, 5], [7, 14]];
chiSquareTest(small); // p = 0.022384
chiSquareTest(small, { correct: true }); // Yates: p = 0.050285
fisherTest(small); // exact: p = 0.048853
Yates's correction shrinks each by in a 2×2 table to allow for the counts being whole numbers. It overcorrects, as the example shows: the exact Fisher test lies between the two.
@ratmath/stats and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.