Optimizations and Improvements
Since the chi-squared cumulative distribution function only uses the following two
features of the complete gamma function, we don't need a general approach. We can
cheat and use the following two values, which are reasonably precise.
If we use proper Fraction values, then we can design a function with a few
simple cases: an integer value, a Fraction value with 1 in the denominator,
and a Fraction value with 2 in the denominator. We can use the Fraction value
as follows:
sqrt_pi = Fraction(677622787, 382307718)
def Gamma_Half(k):
if isinstance(k,int):
return fact(k-1)
elif isinstance(k,Fraction):
if k.denominator == 1:
return fact(k-1)
elif k.denominator == 2:
n = k-Fraction(1,2)
return fact(2*n)/(Fraction(4*n)fact(n))*sqrt_pi
raise ValueError("Can't compute Γ({0})".format(k))
We called the function Gamma_Half to emphasize that this is only appropriate for
whole numbers and halves. For integer values, we'll use the fact() function that
was defined previously. For Fraction objects with a denominator of 1, we'll use the
same fact() definition: Γnn=−()1 !.
For the cases where the denominator is 2, we can use the more complex "closed
form" value. We used an explicit Fraction() function for the value 4!nn. We've
also provided a Fraction approximation for the irrational value π.
Here are some test cases:
- Γ()2 1=
- Γ()^524 =
(^1) 1.7724539
Γπ 2
=≈
•
(^3) 0.8862269
22
Γ=≈π