Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 68 ยท Integrals

Numerical Integration

Compute integrals numerically with the trapezoid rule, Simpson's rule and adaptive quadrature using scipy.integrate.quad, and learn how errors behave.

Most real integrals have no neat antiderivative. Experimental data is even worse: you have measurements at discrete times, not a formula at all. Numerical integration (also called quadrature) approximates the definite integral from function values alone.

All methods share one idea: sample the function at a set of points, fit a simple shape through them, and add up the exact areas of those shapes. The shape you choose determines both the formula and how fast the error shrinks. This lesson goes from rectangles to the professional-grade routine in SciPy.

The trapezoid rule

Instead of flat-topped rectangles as in The Integral as Accumulated Change, join neighbouring sample points with straight lines. Each strip becomes a trapezoid with area (f(x_i) + f(x_{i+1})) / 2 * h. Summing gives

T = h * ( f0/2 + f1 + f2 + ... + f_{n-1} + fn/2 )

where h = (b - a)/n. Its error is proportional to h**2 times the second derivative: halve h, and the error drops by roughly four.

Simpson's rule

Simpson's rule fits a parabola through each pair of strips, using three points at a time. With an even number of strips n:

S = h/3 * ( f0 + 4*f1 + 2*f2 + 4*f3 + ... + 4*f_{n-1} + fn )

The weights alternate 4, 2, 4, 2. Parabolas follow curves much better than lines, so the error is proportional to h**4 times the fourth derivative. Halving h cuts the error by about sixteen. Simpson's rule is exact for polynomials up to degree three.

flowchart LR
    A["Rectangles<br/>error ~ h"] --> B["Trapezoids<br/>error ~ h^2"]
    B --> C["Simpson<br/>error ~ h^4"]

Each rule uses a more flexible shape and gains accuracy per sample point.

Python Trapezoid and Simpson from scratch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at how the Simpson error collapses much faster than the trapezoid error. Each doubling of n divides the trapezoid error by about 4 and the Simpson error by about 16.

Choosing a step size

How many points do you need? You rarely know the true error, so engineers use step halving: compute with n and 2n strips and compare. If the two answers agree to the digits you need, stop. Since the error scales like h**p, the gap between two successive estimates is itself a good estimate of the error.

Python Stop when the answer settles

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This integral, the area under a Gaussian bell curve, has no elementary antiderivative, so a numerical answer is the only way to a number.

Adaptive quadrature and scipy.integrate.quad

A uniform grid wastes effort: it uses as many points where the function is flat as where it wiggles. Adaptive quadrature spends effort where the function is difficult. It estimates the error on each sub-interval and splits only those that fail the tolerance.

scipy.integrate.quad(f, a, b) is the standard tool. It returns two numbers: the value and an estimate of the absolute error. It also handles infinite limits with np.inf, which we use in Improper Integrals and Convergence.

Python quad returns a value and an error estimate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The points=[0.3] argument tells quad where the trouble is, so it does not miss the narrow peak. When an integrand has a known kink, jump or peak, give the location.

Integrating data instead of formulas

If you only have measurements, use np.trapezoid (the trapezoid rule on arbitrary, possibly uneven samples) or scipy.integrate.simpson. You cannot ask for more points, so the sample spacing sets the accuracy.

Python Integrating measured data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The two estimates differ slightly. Neither is "right"; the difference warns you of the uncertainty that coarse sampling creates.

Where numerical integration fails

  • Singularities: an integrand that blows up inside the interval (like 1/sqrt(x) at 0) breaks fixed-grid methods. Use quad, which handles many endpoint singularities, or substitute first.
  • Oscillation: fast wiggles need many points per wave.
  • Discontinuities: split the interval at the jump.
  • Noise: integration averages noise down, whereas differentiation amplifies it. This is why integrating data is far safer than differentiating it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. If you halve the step size h, roughly how does the trapezoid-rule error change?

    The trapezoid error is proportional to h**2, so halving h divides the error by about 4.
  2. 2. What condition does Simpson's 1/3 rule place on the number of strips?

    Parabolas are fitted through three points, using two strips at a time, so the strip count must be even.
  3. 3. What does the second value returned by scipy.integrate.quad represent?

    quad returns (value, abserr). The second number estimates how far the value may be from the true integral.
  4. 4. Why is integrating noisy data safer than differentiating it?

    Summing smooths random errors; dividing differences by a small step makes them larger.

Summary

  • Numerical integration samples the integrand and adds up areas of simple shapes.
  • The trapezoid rule has error ~ h**2; Simpson's rule has error ~ h**4 and needs an even number of strips.
  • Step halving gives a practical error estimate without knowing the exact answer.
  • scipy.integrate.quad is adaptive: it returns the value and an error estimate, and accepts points= for known trouble spots.
  • For measured data use np.trapezoid or scipy.integrate.simpson, and be careful with singularities, jumps and fast oscillations.

Next: Improper Integrals and Convergence.