我的程序使用牛顿算法找到根。如果没有足够的迭代来找到打印根目录尚未找到的根,那么我在最后一部分遇到了麻烦。
for i in range(N):
f= evaluate(p,deg,x0)
s=evaluate(d,deg-1,x0)
if s==0:
print "Can't divide by 0"
return -1
x1=x0 - f/s
print ("Iteration %d" %(i+1))
print "%f" %x0
if abs(x1-x0)<tol:
print "Found a root %f" %x1
return 0
else:
x0=x1
if abs(x1-x0)>tol:
print "root not found"
不知怎的,它似乎跳过最后的if语句并且没有打印任何东西,我试图把它放在不同的地方。当我把它放在前一个if语句之前然后它跳过x0 = x1部分。我对它的错误感到困惑。
N是迭代次数,x0是初始猜测
答案 0 :(得分:1)
显示未找到根目录的逻辑不正确。您不想检查abs(x0 - x1) > tol
,因为这与查找根无关。想一想:x0
和x1
之间的差异可能非常大,但您仍然可以找到找到根的正确轨道。您不希望跳过迭代只是因为x1
与某些迭代上的x0
不同。
更好的方法是将错误语句置于for
循环之外,例如:
for i in range(N):
f = evaluate(p,deg,x0)
s = evaluate(d,deg-1,x0)
if s==0:
print "Can't divide by 0"
return -1
x1=x0 - f/s
print ("Iteration %d" %(i+1))
print "%f" %x0
if abs(x1-x0)<tol:
print "Found a root %f" %x1
return 0
else:
x0=x1
# If we exhaust the for-loop without returning due to
# a found root, then there must have been an error with
# convergence, so just print that at exit.
print "Error: did not converge to the root in %d iterations."%(N)
print "Check your initial guess and check your functions for cyclic points."
答案 1 :(得分:0)
我猜想,永远不会用牛顿的方法做任何事情,你想要的更像是:
x1 = sys.maxint # the first iteration is a throw-away
# you could do this a different way, but you have a lot of global
# variables that I don't know how to handle.
for i in range(N):
# ....
if abs(x1-x0)<tol:
# ...
# you want these two lines together, somehow.
x0 = x1
x1 = x0 - f/s
#...
# no "else" down here
# no "if abs(x1-x0)>tol:", because it's taken care of by the return(0)
# earlier. Also note the unindent.
print "root not found"