Search code examples
pythonscipyscipy-optimize

Can "fsolve (scipy)" find many roots of a function?


I read in the scipy documentation (https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fsolve.html) that fsolve : Find the rootS of a function. But even, with a simple example, I obtained only one root

def my_eq(x):
    y = x*x-1
    return y

roots = fsolve(equation,0.1)
print(roots)

So, is it possible to obtain multiple roots with fsolve in one call ?

For other solvers, it is clear in the doc (https://docs.scipy.org/doc/scipy/reference/optimize.html#id2). They Find a root of a function

(N.B. I know that multiple root finding is difficult)


Solution

  • Apparently, the docs are a bit vague in that respect. The plural roots refers to the fact that both scipy.optimize.root and scipy.optimize.fsolve try to find one N-dimensional point x (root) of a multivariate function F: R^N -> R^N with F(x) = 0.

    However, if you want to find multiple roots of your scalar function, you can write it as a multivariate function and pass different initial guesses:

    import numpy as np
    from scipy.optimize import fsolve
    
    def my_eq(x):
        y1 = x[0]*x[0]-1
        y2 = x[1]*x[1]-1
        return np.array([y1, y2])
    
    x0 = [0.1, -0.1]
    roots = fsolve(my_eq,[0.1, -0.1])
    print(roots)
    

    This yields all roots [1, -1].