简体   繁体   中英

Python: numpy.ndarray object not callable error for root-finding function

I've been trying to figure out how to use Python to find roots. If I'm understanding the documentation correctly, scipy.optimize.newton(f,x_o) can be used to find roots, f is a function and x_o an initial guess at the root.

The functions I'm working with are all polynomials and for the purposes I've ever used Python for (interpolation and line-fitting) it's always been sufficient to express a polynomial by an array of coefficients. Defining f in this manner gives me a numpy.ndarray error and I'm assuming it's because I'm giving f as an array and newton(f,x_o) is expecting a function for f.

I'm pretty inexperienced with Python and when I came across this I realized I actually don't know how to define generally f without having to define another variable that'll limit it to an interval. For some arbitrary polynomial, eg f = 2x^2 + 7, is there a way to define f without having to give an interval for x? Normally I'm used to having to also define x = arange(n) or something like that which limits it to an interval.

You're right, the error is because of the form of f . If you take a look at the scipy documentation for the newton function (here http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.newton.html ), you can see that you have to provide a function f(x,a,b,c) with a,b,c as arguments.

if you then provide a function

def f(x, a, b, c):
    return a*x**2 + b*x + c

and then call the newton method as follows:

root = scipy.optimize.newton(f, x0, args=(a, b, c))

the variable root will contain the approximate location of the root of your function. Of course you will have to provide values for the parameters a,b,c before you call the method.

Hope it helps. Cheers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM