Numerical Integration (scipy.integrate)
Numerical integration calculates the area under a curve when an analytical anti-derivative does not exist or when working with discrete sensor streams.
1. Adaptive Quadrature: quad
scipy.integrate.quad wraps the Fortran QUADPACK library. It dynamically subdivides the integration domain using an adaptive Gauss-Kronrod 21-point rule, returning both the integral value and an upper bound on the absolute error:
result, abserr = integrate.quad(f, a, b)When an integral evaluates close to zero (e.g. ), pure relative error tolerances cannot be satisfied. Always specify a physically meaningful absolute tolerance epsabs.
Basic Integral, Infinite Limits & Discontinuities
Example
Output:
2. Integrating Sampled Data: trapezoid & simpson
When integrating discrete data points from an experiment, you cannot sample arbitrary points:
trapezoid (Composite Trapezoidal)
First-order composite method. Global error scales as :
from scipy.integrate import trapezoid
area = trapezoid(y, x=x)Comparing Convergence on Sampled Sines
Let’s integrate :
Example
Output:
3. Double & Multiple Integrals (dblquad)
For 2D double integrals , inner limits can depend dynamically on the outer variable:
Example
Output:
4. Try It Yourself
Problem: Work Done by Isothermal Expansion
An ideal gas undergoes isothermal expansion from () to () at for . Compute the expansion work using quad.
Show solution
from scipy import integrate, constants
n, T = 1.0, 300.0
V1, V2 = 1.0e-3, 3.0e-3
W, err = integrate.quad(lambda V: n * constants.R * T / V, V1, V2)
print(f"Work W: {W:.2f} J")