2013-05-02 72 views
1
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 while循環一次f一次小於10^-14,但我不知道如何修改參數,使循環迭代,任何幫助?while block does not expect expected

+0

還有,你是初始化'F = 0.'循環 – wim 2013-05-02 00:58:26

+0

之外其實,'樓FP = 0.'是一個問題語法錯誤是不是? – wim 2013-05-02 01:00:22

+1

@wim - 我不知道語法錯誤,但至少有一個TypeError ... – mgilson 2013-05-02 01:24:46

回答

4

你想要的邏輯or而不是|

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

需要注意的是有邏輯或(or)和按位或(|)之間的運算符優先級的差別。您以前的聲明可能被解析爲:

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

這似乎是這將提高TypeError ...

這可能是更容易編寫:

2

|運營商用於bitwise-OR所以你應該在這裏使用邏輯or,其次return語句也是錯誤的地方,它只會在一次迭代後結束你的循環。

def solve(fvals_sqrt, x0, debug_solve = False): 
    iters = 0 
    f, fp = 0. 
    while f > 10**-14 or -f < 10**-14: 
     f, fp = fvals_sqrt(x0) 
     x0 = x0 - (f/fp) 
     iters = iters+1 
     print + " x = %22.15e in %i iterations " % (x0, iters) 
    print "we're done" 
    return x0, iters 
2

while f > 10**-14 | -f < 10**-14正在使用按位OR,而不是邏輯OR。使用or關鍵字:

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

此外,您returnwhile循環內。你不得不放棄這條線向下縮進一個級別:

return x0, iters