Nested integral in Python

元气小坏坏 提交于 2019-12-13 03:50:59

问题


I have an M-dimensional integral where the outer limits over x_M are [0, y], the next limits over x_{M-1} are [0, max(x_M, y-x_M)], .... and the inner integral is over x_1 with limits [0, max(x_2, y-x_M-...-x_2)].

The function/integrand is

(K!/(K-M)!)*(1/(x_1+1)^2)*....*(1/(x_{M-1}+1)^2)*(1/(x_M+1)^{K-M+2})

where K and M are integers such that K >= M >= 1, and K!=K*(K-1)*...*2*1 is K factorial.

How can I do this in Python using scipy.integrate.nquad? I had a similar problem here, but don't know how to extend the code there to my case here.

The LaTeX version of the integral:

My attempt (but the code isn't working. It doesn't give a result between 0 and 1)

K=4
M=2
du = 0.01
#For m=M
def F(u):
      return 1/(1+u)**(K-M+2)
#For m=1,2,...,M-1
def f(u):
     return 1/((1+u))**2

#Recursive function to evaluate the integral
def G(h, m, prev_lim):
    #print(f'h is {h}, and k is {k}')
    if m == M:
        res = F(h)
    else:
        res =  0
        u = prev_lim
        while u < h:
            res += G(h-u, m+1, u)*f(u)*du
            u += du
    return (math.factorial(K)/math.factorial(K-M))*res

print(G(2, 1, 0))

来源:https://stackoverflow.com/questions/51958138/nested-integral-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!