Computing the complete gamma function

The complete gamma function is a bit more difficult to implement than the incomplete gamma function. There are a number of different approximations. For more information, visit http://dlmf.nist.gov/5. There's a version available in the Python math library. It represents a broadly useful approximation that is designed for many situations.

We're not interested in a completely general implementation of the complete gamma function. We're interested in just two special cases: integer values and halves. For these two special cases, we can get exact answers, and don't need to rely on an approximation.

For integer values,  . The complete gamma function for integers can rely on the factorial function we defined previously.

For values which are halves, there's a special form:  . This includes an irrational value, , so we can only represent this approximately using float or Fraction objects.

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 shown in the following code:

sqrt_pi = Fraction(677_622_787, 382_307_718)

from typing import Union
def Gamma_Half(
k: Union[int, Fraction]
) -> Union[int, Fraction]:
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(f"Can't compute Γ({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.

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 . We've also provided a Fraction approximation for the irrational value .

Here are some test cases:

These can also be shown as proper Fraction values. The presence of irrational numbers (square roots, and ) tends to create large, hard-to-read fractions. We can use something like this to create easier-to-read fractions:

>>> g = Gamma_Half(Fraction(3, 2))
>>> g.limit_denominator(2_000_000)
Fraction(291270, 328663)  

This provides a value where the denominator has been limited to be less than two million; this provides pleasant-looking, six-digit numbers that we can use for unit test purposes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset