Example of python code to create a Chi-square table. Note: the code works only with a degree of freedom (df) greater than 2, since the code is based of the Newton method with starting value the approximation x0=df. This approximation does not work for df =1 and 2 (problem of convergence) but work well with df > 2.
from scipy import misc
from scipy import stats
PValueList = [0.995, 0.99, 0.975, 0.95, 0.90, 0.10, 0.05, 0.025, 0.01, 0.005]
global pvalue, dfreedom
def newtons_method(f, x, tolerance=0.0001):
while True:
x1 = x - f(x) / misc.derivative(f, x)
t = abs(x1 - x)
if t < tolerance:
break
x = x1
return x
def f(x):
return 1 - stats.chi2.cdf(x, dfreedom) - pvalue
print( 'df\p' , '| ', PValueList[0], ' | ', PValueList[1], ' | ', PValueList[2], ' | ', \
PValueList[3], ' | ', PValueList[4], ' | ', PValueList[5], ' | ', \
PValueList[6], ' | ', PValueList[7], ' | ', PValueList[8], ' | ', \
PValueList[9] )
for i in range(3,10):
dfreedom = i
Result = []
for pvalue in PValueList:
x0 = dfreedom # x0 approximation
x = newtons_method(f, x0)
Result.append(x)
for i in range(10):
Result[i] = round(Result[i],3)
print( dfreedom, ' | ', Result[0], ' | ', Result[1], ' | ', Result[2], ' | ', Result[3], ' | ', \
Result[4], ' | ', Result[5], ' | ', Result[6], ' | ', Result[7], ' | ', \
Result[8], ' | ', Result[9] )