2013-05-01 249 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