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

标签 python

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

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,因为这与查找根无关。想一想: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."

关于python - 在 python 中格式化 if-else 语句时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10116087/

相关文章:

Python删除额外的特殊unicode字符

结合for循环和if语句的Pythonic方式

python - 在字典列表中搜索 Python 字典值的最佳方法是什么?

python - 如何让 Python Interactive Shell 打印西里尔字符?

python - 什么库最适合 python 中的 GUI?

python - 如何使用 PIL 显示值为 [0, 1] 的图像

python - python中的二进制否定

python - 如何在 Jenkins + Docker 中为 PostgreSQL 以外的数据库指定不同的名称

python - 如何在 Django 1.4 中自定义管理过滤器

python - 如何在 Python 中使用 GLib.Array?