How to Use the Scipy integrate.quad() Method in Python

Contents
In this article, you will learn how to use the Scipy integrate.quad() method in Python.
Scipy integrate.quad() Method
The scipy.integrate.quad() method is a function from the scipy.integrate module that computes a definite integral of a given function over a specified interval. The integral is calculated using the Gauss-Kronrod quadrature algorithm, which is a widely used numerical integration method.
Here’s how to use scipy.integrate.quad() method in Python:
Import the necessary modules:
import scipy.integrate as integrate
Define the function you want to integrate:
The function should take a single argument (the variable of integration) and return a single value:
def integrand(x):
return x**2
Call the quad() method:
Call the quad() method with the integrand function and the limits of integration as arguments. The limits of integration should be specified as a tuple (lower limit, upper limit):
result, error = integrate.quad(integrand, 0, 1)
The quad() method returns two values:
The result of the integration and an estimate of the error in the result. You can assign these values to variables for later use:
print(result, error)
Putting it all together, here’s an example that integrates the function x^2 over the interval [0, 1]:
import scipy.integrate as integrate
def integrand(x):
return x**2
result, error = integrate.quad(integrand, 0, 1)
print(result, error)
The output should be 0.33333333333333337 3.700743415417189e-15, which is the result of the integration and an estimate of the error.