Skip to main content
 首页 » 编程设计

python之在 python 中格式化 if-else 语句时遇到问题

2025年05月04日6lhb25

我的程序使用牛顿算法求根。如果没有足够的迭代来找到要打印的根,我在最后一部分遇到了问题,即根未找到。

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

请您参考如下方法:

显示找不到根的逻辑不正确。您不想检查 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."