python-scipyHow can I use Python and SciPy to find the zeros of a function?
Using Python and SciPy to find the zeros of a function can be done with the scipy.optimize.fsolve function. This function takes a function, and an initial guess, and returns the zero of the function.
For example, to find the zero of the function f(x) = x^2 + 2x - 3, we can use the following code:
from scipy.optimize import fsolve
def f(x):
return x**2 + 2*x - 3
x_zero = fsolve(f, 0)
print(x_zero)
Output example
[-3.]
The code consists of the following parts:
- Importing the
scipy.optimize.fsolvefunction from the SciPy library:from scipy.optimize import fsolve - Defining the function to find the zero of:
def f(x): return x**2 + 2*x - 3 - Calling the
fsolvefunction with the function and initial guess as arguments:x_zero = fsolve(f, 0) - Printing the zero of the function:
print(x_zero)
Helpful links
More of Python Scipy
- 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 can I use Python and SciPy to calculate quaternion operations?
- How do I create a 2D array of zeros using Python and NumPy?
- How do I use Scipy zeros in Python?
- How can I use Python Numpy to select elements from an array based on multiple conditions?
- How can I use Python and SciPy to read and write WAV files?
- How do I use the NumPy transpose function in Python?
- How can I use Python and SciPy to perform a Short-Time Fourier Transform?
See more codes...