# How to create a Chi-square table using python ?

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, ' | ', PValueList, ' | ', PValueList, ' | ', \`
`                      PValueList, ' | ', PValueList, ' | ', PValueList, ' | ', \`
`                      PValueList, ' | ', PValueList, ' | ', PValueList, ' | ', \`
`                      PValueList )`

`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, ' | ', Result, ' | ', Result, ' | ', Result, ' | ', \`
`          Result, ' | ', Result, ' | ', Result, ' | ', Result, ' | ', \`
`          Result, ' | ', Result )`
```
Image

of 