gpt4 book ai didi

python - 递归计算迭代次数

转载 作者:太空宇宙 更新时间:2023-11-04 10:26:31 25 4
gpt4 key购买 nike

我试图通过这个递归来跟踪迭代,但“iter”总是返回 1。

def compute_root(poly, x_0, epsilon): ##Using Newton's method
iter = 0
try:
if abs(evalpoly(poly,x_0)) < epsilon:
return '%s is the root. Took %s iterations.'%(x_0,iter)
else:
iter += 1
x_1 = x_0 - (evalpoly(poly,x_0)/evalderiv(poly,x_0))
return compute_root(poly, x_1, epsilon)

except ZeroDivisionError:
print 'No root.'

我想这是因为我必须实际返回 iter += 1 但我不确定。 . .对不起,如果这是一个基本问题。谢谢!

最佳答案

您应该将 iter 传递给您正在递归调用的函数:

def compute_root(poly, x_0, epsilon, iter=None): ##Using Newton's method
if iter is None:
iter = 0
try:
if abs(evalpoly(poly,x_0)) < epsilon:
return '%s is the root. Took %s iterations.'%(x_0,iter)
else:
iter += 1
x_1 = x_0 - (evalpoly(poly,x_0)/evalderiv(poly,x_0))
return compute_root(poly, x_1, epsilon, iter=iter)

except ZeroDivisionError:
print 'No root.'

关于python - 递归计算迭代次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29068945/

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