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.
- Numerical integration with quad
- Infinite limits and functions with no antiderivative
- Exact integrals with sympy.integrate
- 1
f(x) = x**2The curve - 2
[0, 3]The interval - 3
9.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.
quad(f, 0, 3)📏 Add up thin strips to measure the areaerror🎯 How far the measurement might be offsp.integrate(f, x)📐 Use the shape's formula instead of measuring(x, 0, 3)📍 Where the field starts and endsAn 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
quad(f, a, b)returns a pair: the value and an estimate of its error.- The function can be a
lambdaor any Python function of one number. - Use
math.infas a limit for an integral to infinity. 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.simpsonornp.trapezoid. - Integrals over two or more variables: use
dblquad,tplquadornquad.
Example code
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)))
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.
- Change the function or the data and predict the result before running.
- Compare the numerical answer with the exact one from SymPy or a hand calculation.
- Plot the result with Matplotlib to see what the numbers mean.
Common mistakes
Printing the whole result of quad
quad returns a tuple, so the area prints together with the error estimate.
print(quad(f, 0, 3))
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.
sp.integrate(math.sin(x), x)
sp.integrate(sp.sin(x), x)
Finished this lesson?
Mark it as learned to track your progress.
Tools for this lesson
- Graph Plotter Online: Plot Points and FunctionsPlot points, a pasted table or functions like sin(x) online and download the graph as a PNG. Free graph maker that also gives you the Python Matplotlib code.
- How to Plot a Graph in Python Online (Matplotlib Examples)Plot a graph in Python online with Matplotlib: lines, functions like sin(x), data from a CSV, bar and pie charts. Run each example in your browser.
- NumPy Online: Run NumPy Code in Your BrowserA NumPy playground with no install: arrays, statistics, linear algebra, random numbers and broadcasting. NumPy 2, pandas and SciPy ready to import.