Search code examples
pythonscipyinfgamma

Estimate ratio of two gamma functions when individual functions return inf value


I'm estimating the ratio of two gamma functions. Both estimates for gamma(x) and gamma(y) are very large ( > 10^300) but the ratio of the two should be fairly small.

from scipy.special import gamma
gamma(x) / gamma(y)

Unfortunately, there is a point where gamma(x) is too large and the scipy returns an inf value. Is there a way to stop this, increase the threshold, or alternatively calculate this ratio?

Thanks


Solution

  • Assuming x and y are real and positive you can use the following identity:

    a / b = e^(ln(a) - ln(b))
    

    I can suggest using gmpy2 for the arbitrary precision calculation. It has gmpy2.lgamma, which returns the logarithm of the gamma function, and you can use gmpy2.exp to convert from the logarithm form to your desired ratio.