Code python permettant de construire une table du test chi2. Le code fonctionne pour des dégrées de liberté (degrees of freedom df) strictement supérieurs à 2 (car le code utilise la méthode de Newton avec comme valeur de départ l'approximation x0=df, cependant cette approximation grossière ne marche pas pour df = 1 et 2 (problème de convergence) mais fonctionne très bien pour df > 2). Pour construire une nouvelle table vous pouvez changer la liste des p-values (PValueList) et/ou l'intervalle des dégrées de liberté (Exemple entre 300 et 400: range(300,401) ).

from scipy import miscfrom scipy import statsPValueList = [0.995, 0.99, 0.975, 0.95, 0.90, 0.10, 0.05, 0.025, 0.01, 0.005]global pvalue, dfreedomdef newtons_method(f, x, tolerance=0.0001):while True:x1 = x - f(x) / misc.derivative(f, x)t = abs(x1 - x)if t < tolerance:breakx = x1return xdef f(x):return 1 - stats.chi2.cdf(x, dfreedom) - pvalueprint( '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 = iResult = []for pvalue in PValueList:x0 = dfreedom # x0 approximationx = 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] )
