Search code examples
pythonsolvergamma-distribution

Solving function containing gamma in Python


I'm quite new to programming with python.

I was wondering, if there is a smart way to solve a function, which includes a gamma function with a certain shape and scale.

I already created a function G(x), which is the cdf of a gamma function up to a variable x. Now I want to solve another function including G(x). It should look like: 0=x+2*G(x)-b. Where b is a constant.

My code looks like that:

b= 10

def G(x): 
  return gamma.cdf(x,a=4,scale=25)

f = solve(x+2*G(x)-b,x,dict=True)

How is it possible to get a real value for G(x) in my solve function?

Thanks in advance!


Solution

  • To get roots from a function there are several tools in the scipy module.

    Here is a solution with the method fsolve()

    from scipy.stats import gamma
    from scipy.optimize import fsolve
    
    def G(x): 
      return gamma.cdf(x,a=4,scale=25)
    
    # we define the function to solve
    def f(x,b):
      return x+2*G(x)-b
    
    b = 10
    init = 0. # The starting estimate for the roots of f(x) = 0.
    roots = fsolve(f,init,args=(b))
    
    print roots
    

    Gives output :

    [9.99844838]
    

    Given that G(10) is close to zero this solution seems likely

    Sorry, I didn't take into account your dict=True option but I guess you are able to put the result in whatever structure you want without my help.