0

我试图创建一个使用辛普森方法解决多个积分的函数,我的想法是一个一个地积分变量,直到我只剩下一个积分,但我的递归深度超出了我无法弄清楚为什么(我怀疑那是因为我使用了太多的 lambda 函数)。

def simpson(dim:int, f, dom:list, h=0.01): #dim:dimensions, f:function to be integrated, dom:domain, h:step size

    def integrate(f, interval, h):      #integrates single variable function f using simpson's method 
        integral = 0
        x=interval[0]
        while x<interval[1]:
            integral+=h/6*(f(x)+4*f(x+h/2)+f(x+h))
            x+=h
        return integral

    for d in range(dim-1,-1,-1):            #integrate out variables one by one
        if d==0:
            return integrate(lambda x:f([x]), dom[0], h)
        f = lambda x: integrate(lambda y:f([*x,y]), dom[d], h) #new function that takes one less variable (last variable integrated out)
#test function of two variables (takes input as a vector)   
def T(x):                        
    x,y = x
    return -x**2-2*y**2+2*x*y+2*x+72
print(simpson(2, T, [(0,8),(0,6)])/48)
4

0 回答 0