Skip to Content
ModulesSciPy TutorialNumerical Integration

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. ∫02πsin⁡(x)dx=0\int_0^{2\pi} \sin(x) dx = 0), 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 (xi,yi)(x_i, y_i) from an experiment, you cannot sample arbitrary points:

First-order composite method. Global error scales as O(h2)O(h^2):

from scipy.integrate import trapezoid area = trapezoid(y, x=x)

Comparing Convergence on Sampled Sines

Let’s integrate ∫0πsin⁡(x)dx=2.0\int_0^\pi \sin(x) dx = 2.0:


Example

Output:



3. Double & Multiple Integrals (dblquad)

For 2D double integrals ∬f(y,x)dydx\iint f(y, x) dy dx, 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 V1=1 LV_1 = 1\text{ L} (10−3 m310^{-3}\text{ m}^3) to V2=3 LV_2 = 3\text{ L} (3×10−3 m33 \times 10^{-3}\text{ m}^3) at T=300 KT = 300\text{ K} for n=1 moln = 1\text{ mol}. Compute the expansion work W=∫V1V2nRTVdVW = \int_{V_1}^{V_2} \frac{n R T}{V} dV 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")

PygroundTry It Out

Compute isothermal gas expansion work from 1L to 3L at 300K.

Output:

Last updated on