Python: Finding multiple roots of nonlinear equation

optimization, python, scipy

Solution

Define your function so that it can take either a scalar or a numpy array as an argument:

>>> import numpy as np
>>> f = lambda x : x * np.cos(x-4)

Then pass a vector of arguments to `fsolve`.

>>> x = np.array([0.0, -0.75])
>>> fsolve(f,x)
array([ 0.        , -0.71238898])

Problem

Assume the following function: `f(x) = x * cos(x-4)` With `x = [-2.5, 2.5]` this function crosses `0` at `f(0) = 0` and `f(-0.71238898) = 0`. This was determined with the following code: ``` import math from scipy.optimize import fsolve def func(x): return x*math.cos(x-4) x0 = fsolve(func, 0.0) # returns [0.] x0 = fsolve(func, -0.75) # returns [-0.71238898] ``` What is the proper way to use `fzero` (or any other Python root finder) to find both roots in one call? Is there a different `scipy` function that does this? `fzero` reference

Original source