2

我的程序使用牛顿算法找到根。如果没有足够的迭代来找到要打印的根,那么我在最后一部分遇到了麻烦。

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 是初始猜测

4

2 回答 2

1

显示未找到根的逻辑不正确。您不想检查abs(x0 - x1) > tol,因为这与查找根无关。想一想:两者之间的差异可能非常大x0x1但您仍然可以在正确的轨道上找到根。您不希望仅仅因为与某些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."
于 2012-04-12T01:28:07.723 回答
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"
于 2012-04-12T01:24:00.580 回答