Math and Science with Python

Integrals in Python: SciPy quad and SymPy integrate

Get the area under a curve as a number with scipy.integrate.quad, or the exact antiderivative with SymPy.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • Numerical integration with quad
  • Infinite limits and functions with no antiderivative
  • Exact integrals with sympy.integrate
quad(lambda x: x**2, 0, 3)
  1. 1f(x) = x**2The curve
  2. 2[0, 3]The interval
  3. 39.000000Area under the curve

Two ways to integrate

The problem

Integrals turn up everywhere in maths and science: distance from speed, work from force, probability from a density curve. Doing them by hand is slow, and some functions, like exp(-x**2), have no antiderivative you can write down at all.

Think of it like this

Numerical integration is like measuring the area of a field by laying many thin strips across it and adding up their areas. Symbolic integration is like having the formula for the field's shape, so you can work out the area exactly with no measuring.

From measuring a field to code
quad(f, 0, 3)📏 Add up thin strips to measure the area
error🎯 How far the measurement might be off
sp.integrate(f, x)📐 Use the shape's formula instead of measuring
(x, 0, 3)📍 Where the field starts and ends
Numbers from SciPy, formulas from SymPy.
In one sentence

An integral adds up a quantity over an interval, which is the area under the curve. scipy.integrate.quad computes a definite integral numerically, and sympy.integrate finds integrals exactly with symbols.

Key points

  1. quad(f, a, b) returns a pair: the value and an estimate of its error.
  2. The function can be a lambda or any Python function of one number.
  3. Use math.inf as a limit for an integral to infinity.
  4. sp.integrate(expr, x) gives the antiderivative; sp.integrate(expr, (x, a, b)) gives an exact number.

When should you use it?

  • Areas, volumes, work and distance in physics and engineering.
  • Probabilities from a probability density.
  • Checking an integral you worked out by hand.

When not to use it

  • You only have sampled data points, not a function: use scipy.integrate.simpson or np.trapezoid.
  • Integrals over two or more variables: use dblquad, tplquad or nquad.

Example code

Open in editor →
main.py
import math
from scipy.integrate import quad
import sympy as sp

# Numerical: integrate x**2 from 0 to 3 with SciPy
area, error = quad(lambda x: x**2, 0, 3)
print(f"quad x**2 on [0, 3]: {area:.6f}")
print("Error estimate below 1e-10:", error < 1e-10)

# A function with no simple antiderivative: exp(-x**2) from 0 to 1
value, _ = quad(lambda x: math.exp(-x**2), 0, 1)
print(f"quad exp(-x**2) on [0, 1]: {value:.6f}")

# Infinite limits work too
value, _ = quad(lambda x: math.exp(-x), 0, math.inf)
print(f"quad exp(-x) on [0, inf): {value:.6f}")

# Exact: SymPy gives the antiderivative and the definite integral
x = sp.symbols("x")
print("Antiderivative of x*sin(x):", sp.integrate(x * sp.sin(x), x))
print("Exact integral of x**2 on [0, 3]:", sp.integrate(x**2, (x, 0, 3)))
Get a Run button for this example

Result of running the code

quad x**2 on [0, 3]: 9.000000
Error estimate below 1e-10: True
quad exp(-x**2) on [0, 1]: 0.746824
quad exp(-x) on [0, inf): 1.000000
Antiderivative of x*sin(x): -x*cos(x) + sin(x)
Exact integral of x**2 on [0, 3]: 9

Code explanation

quad takes a function and the two limits and returns two numbers, the area and an estimate of its error, which is why the result is unpacked into area and error. The integral of x**2 from 0 to 3 is 9, and quad also handles exp(-x**2), which has no simple antiderivative, and the infinite limit math.inf. SymPy works with the symbol x instead of numbers: integrate(x * sin(x), x) returns the antiderivative -x*cos(x) + sin(x), and passing the tuple (x, 0, 3) gives the exact definite integral 9.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change the function or the data and predict the result before running.
  2. Compare the numerical answer with the exact one from SymPy or a hand calculation.
  3. Plot the result with Matplotlib to see what the numbers mean.
Run in the Python compiler →

Common mistakes

Printing the whole result of quad

quad returns a tuple, so the area prints together with the error estimate.

Problem
print(quad(f, 0, 3))
Fix
area, error = quad(f, 0, 3)
print(area)

Using math functions with SymPy symbols

math.sin cannot work with a symbol; use the SymPy version.

Problem
sp.integrate(math.sin(x), x)
Fix
sp.integrate(sp.sin(x), x)

Finished this lesson?

Mark it as learned to track your progress.

Tools for this lesson