TExcelTAD
Home › SciPy › SciPy Integration

SciPy Integration

An integral adds up a quantity that changes continuously: the area under a curve, the distance travelled from a varying speed, the total energy used from a power reading. Many integrals have no neat formula, so we compute them numerically. The scipy.integrate module has two families of tools: one for integrating a function you can evaluate anywhere, and one for integrating sampled data.

Integrating a function with quad

quad(f, a, b) integrates f(x) from a to b using an adaptive algorithm from the QUADPACK library. It returns two numbers: the result and an estimate of the absolute error.

python · try it yourself
import numpy as np
from scipy.integrate import quad

value, err = quad(lambda x: x ** 2, 0, 3)
print(f"integral of x^2 from 0 to 3 = {value:.6f}  (exact: 9)")
print(f"error estimate = {err:.1e}")

value, err = quad(np.exp, 0, 1)
print(f"integral of e^x from 0 to 1 = {value:.6f}  (exact: {np.e - 1:.6f})")
integral of x^2 from 0 to 3 = 9.000000  (exact: 9)
error estimate = 1.0e-13
integral of e^x from 0 to 1 = 1.718282  (exact: 1.718282)

The error estimate tells you how much to trust the answer; for smooth functions it is usually close to machine precision.

Infinite limits and extra arguments

Use np.inf for limits that go to infinity. If your function takes extra parameters, pass them with args=:

python · try it yourself
import numpy as np
from scipy.integrate import quad

# The bell curve e^(-x^2) over the whole real line equals sqrt(pi)
value, _ = quad(lambda x: np.exp(-x ** 2), -np.inf, np.inf)
print(f"Gaussian integral = {value:.6f}, sqrt(pi) = {np.sqrt(np.pi):.6f}")

# Energy used by a device whose power decays: P(t) = P0 * e^(-t/tau)
def power(t, p0, tau):
    return p0 * np.exp(-t / tau)

energy, _ = quad(power, 0, 60, args=(100.0, 20.0))   # watts over 60 s
print(f"energy in the first minute = {energy:.1f} J")
Gaussian integral = 1.772454, sqrt(pi) = 1.772454
energy in the first minute = 1900.4 J

Tricky integrands

Functions with sharp peaks, jumps or singularities make an adaptive integrator work much harder, and in bad cases fool it entirely. Two options help: points= tells quad where the difficult spots are, and limit= allows more subdivisions. Passing full_output=1 adds a dictionary of diagnostics, including the number of function evaluations neval.

python · try it yourself
import numpy as np
from scipy.integrate import quad

# |x - 1| has a kink at x = 1; full_output=1 also returns diagnostics
v1, _, info1 = quad(lambda x: abs(x - 1), 0, 3, full_output=1)
v2, _, info2 = quad(lambda x: abs(x - 1), 0, 3, points=[1], full_output=1)
print(f"without hint: {v1:.6f} using {info1['neval']} evaluations")
print(f"points=[1]  : {v2:.6f} using {info2['neval']} evaluations  (exact 2.5)")

# 1/sqrt(x) is infinite at 0, but its integral from 0 to 1 is finite (= 2)
v3, _ = quad(lambda x: 1 / np.sqrt(x), 0, 1)
print(f"integral of 1/sqrt(x) on [0, 1] = {v3:.6f}")
without hint: 2.500000 using 189 evaluations
points=[1]  : 2.500000 using 42 evaluations  (exact 2.5)
integral of 1/sqrt(x) on [0, 1] = 2.000000

Double and triple integrals

dblquad(f, a, b, gfun, hfun) integrates over a 2-D region. Watch the argument order: the function receives (y, x) — the inner variable first. The inner limits may be numbers or functions of x:

python · try it yourself
import numpy as np
from scipy.integrate import dblquad, tplquad

# Volume under z = x*y over the rectangle 0<=x<=2, 0<=y<=1
vol, _ = dblquad(lambda y, x: x * y, 0, 2, 0, 1)
print(f"volume = {vol:.4f}")

# Area of the unit circle: x from -1 to 1, y between -sqrt(1-x^2) and +sqrt(1-x^2)
area, _ = dblquad(lambda y, x: 1.0, -1, 1,
                  lambda x: -np.sqrt(1 - x ** 2), lambda x: np.sqrt(1 - x ** 2))
print(f"circle area = {area:.6f}  (pi = {np.pi:.6f})")

# Volume of the unit cube with tplquad
cube, _ = tplquad(lambda z, y, x: 1.0, 0, 1, 0, 1, 0, 1)
print(f"cube volume = {cube:.1f}")
volume = 1.0000
circle area = 3.141593  (pi = 3.141593)
cube volume = 1.0

Integrating sampled data

Often you don't have a formula, only measurements. trapezoid() joins the points with straight lines; simpson() fits parabolas through them and is usually more accurate for smooth data. cumulative_trapezoid() returns the running total:

python · try it yourself
import numpy as np
from scipy.integrate import trapezoid, simpson, cumulative_trapezoid

# Speed of a car (m/s) sampled every 2 seconds
t = np.array([0, 2, 4, 6, 8, 10])
v = np.array([0.0, 6.0, 11.0, 15.0, 18.0, 20.0])

print(f"distance (trapezoid): {trapezoid(v, x=t):.2f} m")
print(f"distance (Simpson)  : {simpson(v, x=t):.2f} m")
print("running distance   :", cumulative_trapezoid(v, x=t, initial=0))
distance (trapezoid): 120.00 m
distance (Simpson)  : 120.83 m
running distance   : [  0.   6.  23.  49.  82. 120.]
Function Input Notes
quad a Python function Adaptive, very accurate, returns an error estimate
dblquad, tplquad, nquad a function of 2, 3 or n variables Inner variable is the first argument
fixed_quad, quadrature a function Gaussian quadrature with a fixed number of points
trapezoid sample arrays Straight-line approximation
simpson sample arrays Parabolic approximation, better for smooth data
cumulative_trapezoid sample arrays Running integral

Tip: Prefer quad whenever you can evaluate the function at any point: it chooses where to sample and reports its error. Use trapezoid/simpson only for data that is already sampled.

Test yourself

What does quad(f, a, b) return?

  1. Only the integral value
  2. A tuple: (integral value, estimated absolute error)
  3. An array of sampled values
  4. The antiderivative as a function

With dblquad, in what order does the integrand receive its variables?

  1. (x, y)
  2. (y, x) — the inner variable first
  3. As a single array
  4. Alphabetical order

You only have measured samples of a curve, not a formula. Which function fits best?

  1. quad
  2. dblquad
  3. simpson
  4. solve_ivp