Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Python Problem with a gamma function/error message

  1. Mar 20, 2016 #1


    User Avatar
    Gold Member

    I wrote the following python script in order to try and look how $$\sum_{i=1}^\infty f(n) = \sum_{i=1}^\infty \frac{\Gamma(n+1/2)}{n^2 \Gamma(n)}$$ behaves. However it appears to have some problem with my function f(n) for n=172 and above throwing this error:
    I thought that there was a problem with the function [as division with zero] and so I tried wolframalpha which returns me a non zero value for [itex]\Gamma(172)[/itex] and also a non-infinite value for f(172).
    I even tried a user-defined gamma function I had built in the past, and I got the same result for n=172... [it's highly unlike that my method's the same as scipy's]

    Code (Python):

    from scipy.special import gamma

    def f(n):
        return gamma(n+0.5)/(n**2 * gamma(n))

    def sume(f,N):
        for i in range(1,N+1): result+= f(i)
        return result

    print f(172)
    for i in range(100,200):
        print i," : ",sume(f,i)

  2. jcsd
  3. Mar 20, 2016 #2


    User Avatar
    Science Advisor
    Gold Member
    2017 Award

    gamma(172) = 171! is a huge number. It is probably just too large for the floating point double precision number format of the computer. The limit is about 1.8x10308. gamma(172) is about 1.2x10309. So that is where the number gets too large for the computer to handle.
  4. Mar 20, 2016 #3


    User Avatar
    Staff Emeritus
    Science Advisor

    I wouldn't use the built-in gamma function for large arguments. Dividing two huge numbers is usually very inaccurate.

    I would instead just calculate the expression inside the summation recursively

    [itex]f(n) = \dfrac{\Gamma(n+\frac{1}{2})}{n^2 \Gamma(n)}[/itex]

    So [itex]f(n+1) = \dfrac{\Gamma(n+\frac{1}{2}+1)}{(n+1)^2 \Gamma(n+1)}[/itex]

    Then you use that [itex]\Gamma(x+1) = x \Gamma(x)[/itex] to write this as follows:

    So [itex]f(n+1) = \dfrac{(n+\frac{1}{2})\Gamma(n+\frac{1}{2})}{(n+1)^2 n \Gamma(n)} = \dfrac{n(n+\frac{1}{2})}{(n+1)^2} f(n)[/itex]
  5. Mar 20, 2016 #4

    jim mcnamara

    User Avatar

    Staff: Mentor

Share this great discussion with others via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted