fork(2) download
  1. from math import lgamma, exp, log
  2.  
  3. # Computes P(a, x)
  4. # Regularized lower incomplete gamma function.
  5. def lowergamma(a, x, itmax=100, eps=3.0E-7, fpmin=1.0E-30):
  6. return 1 - uppergamma(a, x, itmax, eps, fpmin)
  7.  
  8. # Computes Q(a, x)
  9. # Regularized upper incomplete gamma function.
  10. # @see Numerical Recipes in Fortran77 (Ch. 6.2 Special Functions).
  11. def uppergamma(a, x, itmax=100, eps=3.0E-7, fpmin=1.0E-30):
  12. assert x >= 0 and a > 0, 'arguments zero or negative'
  13. b=x+1-a
  14. c=1/fpmin
  15. d=1/b
  16. h=d
  17. for i in range(1, 1+itmax):
  18. an=-i*(i-a)
  19. b=b+2
  20. d=an*d+b
  21. if abs(d) < fpmin: d=fpmin
  22. c=b+an/c
  23. if abs(c) < fpmin: c=fpmin
  24. d=1/d
  25. dl=d*c
  26. h=h*dl
  27. if abs(dl-1) < eps:
  28. return h*exp(-x+a*log(x)-lgamma(a))
  29. raise ValueError('a too large, itmax too small')
  30.  
  31. def chisqcdf(x, k):
  32. return lowergamma(k/2, x/2)
  33.  
  34. def pvalue(x, k):
  35. return 1 - chisqcdf(x, k)
  36.  
  37. print(round(pvalue(0.71, 4), 2)) # 0.95
  38. print(round(pvalue(3.36, 4), 2)) # 0.5
  39. print(round(pvalue(9.49, 4), 2)) # 0.05
  40.  
  41. print(round(pvalue(3.66, 3), 2)) # 0.3
  42. print(round(pvalue(6.06, 5), 2)) # 0.3
  43. print(round(pvalue(3.83, 6), 2)) # 0.7
  44.  
  45. print(round(pvalue( 124.352, 100), 2)) # 0.05
  46. print(round(pvalue( 969.484, 1000), 2)) # 0.75
  47. print(round(pvalue( 999.333, 1000), 2)) # 0.5
  48. print(round(pvalue(1029.790, 1000), 2)) # 0.25
  49. print(round(pvalue(1057.724, 1000), 2)) # 0.1
Success #stdin #stdout 0.04s 9984KB
stdin
Standard input is empty
stdout
0.95
0.5
0.05
0.3
0.3
0.7
0.05
0.75
0.5
0.25
0.1