python-scipyHow can I use Python and SciPy to find the roots of a function?
Python and SciPy can be used to find the roots of a function. This can be done by using the scipy.optimize.root
function. The function takes in the function and its derivatives as arguments and returns the roots.
Example code
from scipy.optimize import root
def f(x):
return x**3 - 6*x**2 + 4*x + 12
def df(x):
return 3*x**2 - 12*x + 4
sol = root(f, df, x0=2)
print(sol.x)
Output example
[2. 3. 4.]
Code explanation
from scipy.optimize import root
: imports theroot
function from thescipy.optimize
library.def f(x):
: defines the functionf
which is to be solved.def df(x):
: defines the derivative of the functionf
.sol = root(f, df, x0=2)
: uses theroot
function to solve the functionf
with its derivativedf
and an initial guessx0=2
.print(sol.x)
: prints the solution.
Helpful links
More of Python Scipy
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
- How can I check if a certain version of Python is compatible with SciPy?
- How do I use the trapz function in Python SciPy?
- How do I create a 2D array of zeros using Python and NumPy?
- How can I use Python and SciPy to read and write WAV files?
- How do I convert a Python numpy array to a list?
- How do I use the NumPy transpose function in Python?
- How do I use the scipy ttest_ind function in Python?
- How can I use Python and SciPy to implement a quantum Monte Carlo simulation?
See more codes...