2013-05-01 93 views
0
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=True): 
    """ 
    Solves the sqrt function, using newtons methon. 
    """ 
    fvals_sqrt(x0) 
    x0 = x0 + (f/fp) 
    print x0 

當我嘗試調用函數解決,蟒蛇回報Python變量範圍:與函數作爲參數

NameError: global name 'f' is not defined 

顯然,這是一個範圍的問題,但我怎麼能使用f內我的解決功能?

回答

3

你想這樣的:

def solve(fvals_sqrt, x0, debug_solve=True): 
    """ 
    Solves the sqrt function, using newtons methon. 
    """ 
    f, fp = fvals_sqrt(x0) # Get the return values from fvals_sqrt 
    x0 = x0 + (f/fp) 
    print x0 
3

你打電話給fvals_sqrt()但是不要對返回值做任何事情,所以它們被丟棄。返回變量不會神奇地使它們存在於調用函數中。您的電話應該是像這樣:

f, fp = fvals_sqrt(x0) 

當然,你不需要爲你調用該函數的聲明return使用使用相同的名字來。

3

問題是,你不能從函數調用的任何地方存儲返回值:

f,fp = fvals_sqrt(x0) 
1

您需要展開的fvals_sqrt(x0)結果,這條線

f, fp = fvals_sqrt(x0) 

全球範圍內,您應該嘗試

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(x0, debug_solve=True): 
    """ 
    Solves the sqrt function, using newtons methon. 
    """ 
    f, fp = fvals_sqrt(x0) 
    x0 = x0 + (f/fp) 
    print x0 

solve(3) 

結果

>>> 
3.83333333333