Q: Python: Subtract a float from a function (in order to call scipy.newton()) I want to call scipy.newton(f, x0, df).
I have f defined as
def f(x):
    resf = x**2
    return resf

and df as
def df(x):
    df = 2*x
    return df

I call newton like this
x0 = 1.0    
y0 = 6.0
root = newton(f-y0, x0, df)

Of course I'm getting an error, because I try to subtract a floatfrom a function.
How do I have to define the function f and call newton to find the root of f-y0.
What is the syntax, what are the input arguments?
The following doesn't work: 
 def f(x, y0):
    resf = x**2-y0
    return resf

because then I don't know how to call newton.

A: You can pass an anonymous function like this:
root = newton(lambda x: f(x)-y0, x0, df)


Using a nested function is possible as well:
def difference(x):
    return f(x) - y0

root = newton(difference, x0, df)


A: There is an option args= you can use in scipy.optimize.newton to supply additional parameters. Then the df has to be modified in order to accept that additional parameter as well, which can be simply done by adding *args, **kwargs.
Using functools.partial will be associated with 12% additional run time.
In [26]:
import functools
import scipy.optimize as so

def f(x, y0):
    resf = x**2-y0
    return resf
def df(x, *args, **kwargs):
    df = 2*x
    return df
x0 = 1.0    
y0 = 6.0
so.newton(f, x0, args=(y0,), fprime=df)

Out[26]:
2.449489742783178

In [27]:
%timeit so.newton(f, x0, args=(y0,), fprime=df)
100000 loops, best of 3: 6.54 µs per loop

In [28]:
%timeit so.newton(functools.partial(f, y0=y0), x0, df)
100000 loops, best of 3: 7.4 µs per loop


A: You can use the two-argument version of f() with functools.partial():
def f(x, y0):
    resf = x**2-y0
    return resf

x0 = 1.0    
y0 = 6.0
root = scipy.optimize.newton(functools.partial(f, y0=y0), x0, df)

I have a slight preference for this method over wrapping the one-argument version of f() since it's easier to see that df() is the correct derivative w.r.t. x.
