chi-helper.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #!/usr/bin/python3
  2. from scipy import misc
  3. from scipy import stats
  4. import sys
  5. from locale import atof
  6. # this is a silly program
  7. # it is originally from https://moonbooks.org/Articles/How-to-create-a-Chi-square-table-using-python-/
  8. # but the thing is....it.'s from the era where we still used human beings to lookup in tables like this
  9. # what you *really* want is to query this somehow
  10. #
  11. # Creative Commons Attribution-ShareAlike 4.0 International License.
  12. # CC Ben, the Founder of moonbooks.org
  13. # https://realpython.com/python-command-line-arguments/
  14. PValueList = [atof(sys.argv[1]),atof(sys.argv[2])]
  15. global pvalue, dfreedom
  16. def newtons_method(f, x, tolerance=0.000001):
  17. if tolerance == 0.0:
  18. print( "no difference" )
  19. while True:
  20. x1 = x - f(x) / misc.derivative(f, x)
  21. t = abs(x1 - x)
  22. if t < tolerance:
  23. break
  24. x = x1
  25. return x
  26. def f(x):
  27. return 1 - stats.chi2.cdf(x, dfreedom) - pvalue
  28. print( 'df\p' , ' |\t ', PValueList[0], ' |\t ', PValueList[1] )
  29. for i in range(1,2):
  30. dfreedom = i
  31. Result = []
  32. for pvalue in PValueList:
  33. x0 = dfreedom # x0 approximation
  34. x = newtons_method(f, x0)
  35. Result.append(x)
  36. for i in range( 2):
  37. Result[i] = round(Result[i],3)
  38. print( dfreedom, ' |\t ', Result[0], ' |\t ', Result[1] )