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

When I try to call the function solve, python returns:

NameError: global name 'f' is not defined

Obviously this is a scope issue, but how can I use f within my solve function?

4 Answers 4

3

You want this:

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
Sign up to request clarification or add additional context in comments.

Comments

3

You're calling fvals_sqrt() but don't do anything with the return values, so they are discarded. Returning variables won't magically make them exist inside the calling function. Your call should be like so:

f, fp = fvals_sqrt(x0)

Of course, you don't need to use the same names for the variables as are used in the return statement of the function you're calling.

Comments

3

Problem is that you're not storing the returned value from the function call anywhere:

f,fp = fvals_sqrt(x0)

Comments

1

You need to unfold result of fvals_sqrt(x0), with this line

f, fp = fvals_sqrt(x0)

Globally, you should try

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)

Result

>>> 
3.83333333333

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.