Math and Science with Python

Simpson's Rule in Python

Write composite Simpson's rule yourself, watch the error shrink as n grows, and compare with scipy.integrate.simpson.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • The weights 1, 4, 2, 4, ..., 4, 1
  • Why n must be even
  • scipy.integrate.simpson for sampled data
Weights for n = 6
1
4
2
4
2
4
1

Parabolas instead of straight lines

The problem

Numerical methods courses ask you to approximate integrals with the trapezoidal rule and Simpson's rule and compare their errors. Simpson's rule is also what you use when you only have measured values at equal steps.

Think of it like this

The trapezoidal rule is like tracing a curve with a ruler, using straight pieces. Simpson's rule is like tracing it with a flexible curve that bends through three points at a time, so it hugs the real shape much more closely.

From tracing a curve to code
h = (b - a) / n📏 The width of each piece
4 if i % 2 else 2⚖️ Middle points count four times, joins twice
total * h / 3🧮 Add up the area under the parabolas
n must be even🔢 Parabolas need pairs of pieces
Bend through three points at a time.
In one sentence

Composite Simpson's rule approximates the integral of f on [a, b] with n equal intervals (n even) as h/3 times the sum of f at each point, weighted 1, 4, 2, 4, ..., 4, 1.

Key points

  1. h is the interval width and n must be even, or the function raises ValueError.
  2. Odd-numbered points get weight 4 and even-numbered inner points weight 2.
  3. For sin(x) from 0 to pi the error falls from 9.4e-02 at n = 2 to 1.1e-08 at n = 100.
  4. scipy.integrate.simpson(y, x=x) works on sampled values instead of a function.

When should you use it?

  • Numerical methods assignments.
  • Integrating measured data taken at equal steps.
  • Checking an exact integral.

When not to use it

  • You have the function and just want the answer: scipy.integrate.quad chooses the points for you.
  • Data at uneven steps: pass the actual x values to simpson, or use np.trapezoid.

Example code

Open in editor →
main.py
import math
import numpy as np
from scipy.integrate import simpson

def simpson_rule(f, a, b, n):
    if n % 2:
        raise ValueError("n must be even")
    h = (b - a) / n
    total = f(a) + f(b)
    for i in range(1, n):
        total += (4 if i % 2 else 2) * f(a + i * h)   # weights 1 4 2 4 ... 4 1
    return total * h / 3

# Integral of sin(x) from 0 to pi is exactly 2
for n in [2, 4, 10, 100]:
    approx = simpson_rule(math.sin, 0, math.pi, n)
    print(f"n = {n:>3}  {approx:.10f}  error {abs(approx - 2):.1e}")

# SciPy's simpson works on sampled points
x = np.linspace(0, math.pi, 101)   # 101 points = 100 intervals
print(f"scipy simpson: {simpson(np.sin(x), x=x):.10f}")
Get a Run button for this example

Result of running the code

n =   2  2.0943951024  error 9.4e-02
n =   4  2.0045597550  error 4.6e-03
n =  10  2.0001095173  error 1.1e-04
n = 100  2.0000000108  error 1.1e-08
scipy simpson: 2.0000000108

Code explanation

simpson_rule() splits [a, b] into n equal intervals of width h, where n must be even. The function values get the weights 1, 4, 2, 4, ..., 4, 1, and the sum is multiplied by h / 3. For sin(x) from 0 to pi the exact answer is 2: with n = 2 the estimate is 2.0944, and with n = 100 the error drops to 1.1e-08. SciPy's simpson takes sampled y and x values instead of a function, and with the same 100 intervals gives the same 2.0000000108.

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

Using an odd number of intervals

Simpson's rule pairs up intervals, so n must be even.

Problem
simpson_rule(math.sin, 0, math.pi, 5)
Fix
simpson_rule(math.sin, 0, math.pi, 6)

Confusing points and intervals

101 points make 100 intervals.

Problem
x = np.linspace(0, math.pi, 100)  # 99 intervals
Fix
x = np.linspace(0, math.pi, 101)  # 100 intervals

Finished this lesson?

Mark it as learned to track your progress.

Tools for this lesson