gpt4 book ai didi

python - 超出最大递归深度

转载 作者:太空宇宙 更新时间:2023-11-04 01:22:53 24 4
gpt4 key购买 nike

我收到“超出最大递归深度”错误。

#Defining an example function here
def f(x):
return e**(-2*x)

#命令 def 辛普森 (a, b):
c = (a+b)/2 返回 (b-a)/6*f(a)+4*f(c)+f(b)

#The Adaptive Simpson's formula
def adaptive_simpsons(a,b,tol,comparison):
c = (a+b)/2
left = simpsons(a,c)
right = simpsons(c,b)
if abs((left + right - comparison)/15) < tol:
return (left + right - comparison)/15 + left + right
else:
return adaptive_simpsons(a,c,tol/2,left) + adaptive_simpsons(c,b,tol/2,right)

但是,当我打印时:

print adaptive_simpsons(a,b,tol, simpsons(a,b)), 

我收到错误“超出最大递归深度”

是我的代码做错了什么,还是真的要多次循环这个递归公式?而且,我将如何解决这个问题?

最佳答案

可悲的是,Python 没有进行尾调用优化。因此,您必须序列化您的递归。

同样为了使 TCO 正常工作,您需要重构您的函数(可能添加一个累加器参数)以使其成为尾调用。

关于python - 超出最大递归深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20040882/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com