Skip to main content
 首页 » 编程设计

python之while block 没有按预期循环

2025年05月04日12lonelyxmas

def fvals_sqrt(x): 
    """ 
    Return f(x) and f'(x) for applying Newton to find a square root. 
    """ 
    f = x**2 - 4. 
    fp = 2.*x 
    return f, fp 
 
def solve(fvals_sqrt, x0, debug_solve = False): 
    """ 
    Solves the sqrt function, using newtons methon. 
    """ 
    iters = 0 
    f, fp = 0. 
    while  f > 10**-14 | -f < 10**-14: 
        f, fp = fvals_sqrt(x0) 
        x0 = x0 - (f/fp) 
        iters = iters+1 
        print  + " x = %22.15e in %i iterations " % (x0, iters) 
        return x0, iters 
 
    print "we're done" 

我想要这个 while 循环 once f once 小于 10^-14,但我不确定如何修改参数以使循环可迭代,有帮助吗?

请您参考如下方法:

你想要逻辑or而不是|:

while  f > 10**-14 or -f < 10**-14: 

请注意,逻辑或 (or) 和按位或 (|) 之间的运算符优先级有所不同。您之前的声明可能被解析为:

while (f > (10**-14 | -f)) < 10**-14): 

这似乎会引发 TypeError...

这样写可能更容易:

while abs(f) > 10**-14: