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 therootfunction from thescipy.optimizelibrary.def f(x):: defines the functionfwhich is to be solved.def df(x):: defines the derivative of the functionf.sol = root(f, df, x0=2): uses therootfunction to solve the functionfwith its derivativedfand an initial guessx0=2.print(sol.x): prints the solution.
Helpful links
More of Python Scipy
- How can I use Python and Numpy to parse XML data?
- How do I use Scipy zeros in Python?
- How do I upgrade my Python Scipy package?
- How can I use Python and SciPy to perform a Short-Time Fourier Transform?
- How do I create a 2D array of zeros using Python and NumPy?
- How do I create a zero matrix using Python and Numpy?
- How can I use the x.shape function in Python Numpy?
- How do I use Python and SciPy to create a tutorial PDF?
- How can I use RK45 with Python and SciPy?
- How can I use Python Numpy to select elements from an array based on multiple conditions?
See more codes...