Finding the root of a mathematical function
In this short recipe, we will see how to use SciPy to find the root of a simple mathematical function of a single real variable.
How to do it…
Let's import NumPy, SciPy,
scipy.optimize
, and matplotlib:In [1]: import numpy as np import scipy as sp import scipy.optimize as opt import matplotlib.pyplot as plt %matplotlib inline
We define the mathematical function f(x)=cos(x)-x in Python. We will try to find a root of this function numerically. Here, a root corresponds to a fixed point of the cosine function:
In [2]: f = lambda x: np.cos(x) - x
Let's plot this function on the interval [-5, 5] (using 1000 samples):
In [3]: x = np.linspace(-5, 5, 1000) y = f(x) plt.plot(x, y) plt.axhline(0, color='k') plt.xlim(-5,5)
We see that this function has a unique root on this interval (this is because the function's sign changes on this interval). The
scipy.optimize
module contains a few root-finding functions...