Numerical integration

SciPy · Essentials · 9 min

Areas, probabilities, expectations and totals over time are integrals with no closed form.

scipy.integrate handles two situations.

You have a function. integrate.quad(f, a, b) adaptively samples f until the estimated error is below tolerance. It returns (value, abs_error_estimate). Infinite limits work: quad(f, 0, np.inf). Extra parameters go in args=(...). For trickier integrands, points=[...] marks known kinks or discontinuities, and limit raises the number of subintervals; an IntegrationWarning means the result may be inaccurate. For multiple dimensions there are dblquad, tplquad and nquad, and quad_vec integrates vector-valued functions.

You have samples. When y is measured at points x (sensor readings, a sampled curve), use:

  • integrate.trapezoid(y, x): straight lines between points,
  • integrate.simpson(y, x=x): parabolic segments, more accurate for smooth data,
  • integrate.cumulative_trapezoid(y, x, initial=0): the running integral, for example distance from velocity.

The old names trapz, simps and cumtrapz were removed; use the new ones.

quad is accurate for smooth one-dimensional integrands. For high-dimensional integrals, Monte Carlo methods (scipy.stats.qmc helps generate low-discrepancy points) scale better.

Example

import numpy as np
from scipy import integrate

val, err = integrate.quad(np.sin, 0, np.pi)
print(round(val, 6), err < 1e-10)          # 2.0 True

# Gaussian integral over the whole real line
val, _ = integrate.quad(lambda x: np.exp(-x ** 2), -np.inf, np.inf)
print(round(val, 6), round(np.sqrt(np.pi), 6))   # 1.772454 1.772454

t = np.linspace(0, 10, 11)                 # seconds
v = 3.0 * t                                # velocity, m/s
print(integrate.trapezoid(v, t))           # 150.0 (distance in m)
print(integrate.cumulative_trapezoid(v, t, initial=0)[:4])  # [ 0.   1.5  6.  13.5]

Remember

  • quad(f, a, b) returns (value, error estimate) and accepts infinite limits
  • Use trapezoid, simpson, cumulative_trapezoid for sampled data
  • Watch for IntegrationWarning; mark discontinuities with points=

Watch out for

  • Calling the removed trapz/simps names from old tutorials.

Check yourself

  1. You have temperature readings every minute and want the time-integral. Which function fits?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.scipy.org/doc/scipy/tutorial/integrate.html