Simpson's Rule in Python
Write composite Simpson's rule yourself, watch the error shrink as n grows, and compare with scipy.integrate.simpson.
- The weights 1, 4, 2, 4, ..., 4, 1
- Why n must be even
- scipy.integrate.simpson for sampled data
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.
h = (b - a) / n📏 The width of each piece4 if i % 2 else 2⚖️ Middle points count four times, joins twicetotal * h / 3🧮 Add up the area under the parabolasn must be even🔢 Parabolas need pairs of piecesComposite 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
his the interval width and n must be even, or the function raisesValueError.- Odd-numbered points get weight 4 and even-numbered inner points weight 2.
- For
sin(x)from 0 to pi the error falls from9.4e-02at n = 2 to1.1e-08at n = 100. 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.quadchooses the points for you. - Data at uneven steps: pass the actual x values to
simpson, or usenp.trapezoid.
Example code
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}")
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.
- 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
Using an odd number of intervals
Simpson's rule pairs up intervals, so n must be even.
simpson_rule(math.sin, 0, math.pi, 5)
simpson_rule(math.sin, 0, math.pi, 6)
Confusing points and intervals
101 points make 100 intervals.
x = np.linspace(0, math.pi, 100) # 99 intervals
x = np.linspace(0, math.pi, 101) # 100 intervals
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.