I have a function represented as a narray i. e. y = f(x), where y and x are two narrays.
I am searching for a method that find the roots of f(x).
Reading the scipy documentation, I was able to find just methods that works on user defined functions, like scipy.optimize.root_scalar
. I thought about using scipy.interpolate.interp1d
to get an interpolated version of my function to be used in scipy.optimize.root_scalar
, but I'm not sure it can work and it seems pretty complicated.
Is it there some other function that I can use instead?
Asked
Active
Viewed 573 times
0

Emu
- 1
-
See https://stackoverflow.com/questions/39457469/trying-to-interpolate-linearly-in-python/39458926#39458926; there are other variations in that question, and I expect this question (in one form or another) has been asked many times--but searching for related quesitons is a bit of a challenge. – Warren Weckesser Mar 01 '22 at 00:19
1 Answers
1
You have to interpolate a function defined by numpy arrays as all the solvers require a function that can return a value for any input x, not just those in your array. But this is not complicated, here is an example
from scipy import optimize
from scipy import interpolate
# our xs and ys
xs = np.array([0,2,5])
ys = np.array([-3,-1,2])
# interpolated function
f = interpolate.interp1d(xs, ys)
sol = optimize.root_scalar(f, bracket = [xs[0],xs[-1]])
print(f'root is {sol.root}')
# check
f0 = f(sol.root)
print(f'value of function at the root: f({sol.root})={f0}')
output:
root is 3.0
value of function at the root: f(3.0)=0.0
You may also want to interpolate with higher-degree polynomials for higher accuracy of your root-finding, eg How to perform cubic spline interpolation in python?

piterbarg
- 8,089
- 2
- 6
- 22