python-scipyHow do I use scipy.quad to solve a quadratic equation in Python?
The scipy.quad
function can be used to solve a quadratic equation in Python. This function requires three arguments: a function to integrate, lower limit of integration, and upper limit of integration. The following example code block shows how to use scipy.quad
to solve the quadratic equation x^2 + 2x + 3 = 0
:
from scipy.integrate import quad
def f(x):
return x**2 + 2*x + 3
x_1, _ = quad(f, 0, 1)
x_2, _ = quad(f, -1, 0)
print(x_1, x_2)
Output example
3.0 -2.0
The code can be broken down into the following parts:
from scipy.integrate import quad
: This imports thequad
function from thescipy.integrate
module.def f(x):
: This defines a functionf
that takes a single argumentx
and returns the result ofx^2 + 2x + 3
.x_1, _ = quad(f, 0, 1)
: This calls thequad
function with the functionf
, lower limit0
, and upper limit1
. The result is stored in the variablesx_1
and_
.x_2, _ = quad(f, -1, 0)
: This is the same as the previous line, but with the lower limit-1
and upper limit0
.print(x_1, x_2)
: This prints the values ofx_1
andx_2
.
Helpful links
More of Python Scipy
- How do I create a 2D array of zeros using Python and NumPy?
- How can I use Python and SciPy to find the zeros of a function?
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How can I use Python Scipy to zoom in on an image?
- How do I use Python Scipy to perform a Z test?
- How can I use the x.shape function in Python Numpy?
- How can I use Python and Numpy to parse XML data?
- How do I use scipy's griddata function in Python?
- How to use Python, XML-RPC, and NumPy together?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
See more codes...