Chi-Square Goodness of Fit

medium
Unit 17 · Hypothesis Testing II0/3 to milestone

Is a die fair? Are signups spread evenly across weekdays? The goodness-of-fit statistic compares observed counts OO with expected counts EE:

χ2=∑(O−E)2E\chi^2 = \sum \frac{(O - E)^2}{E}

Implement gof(observed, expected_probs) returning (chi2, dof, p_value), where expected counts are n * p and dof = k - 1. For the p-value, use the regularised upper incomplete gamma function Q(dof/2, χ2/2)Q(\text{dof}/2,\ \chi^2/2), computed with this series for P(a,x)P(a, x) (then Q=1−PQ = 1 - P):

P(a,x)=xae−xΓ(a+1)∑n=0∞xn(a+1)(a+2)⋯(a+n)P(a, x) = \frac{x^a e^{-x}}{\Gamma(a+1)}\sum_{n=0}^{\infty}\frac{x^n}{(a+1)(a+2)\cdots(a+n)}

Sum until terms fall below 1e-15 relative to the total.

#hypothesis-testing#categorical2 visible + 1 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Chi-Square Goodness of Fit · TechGradify