Computing Library › Worked Examples
Worked Examples

Simpson's Rule Integration

Approximate a definite integral with Simpson's rule, fitting parabolas over pairs of intervals for fourth-order accuracy.

Problem

Simpson's rule estimates a definite integral by fitting a parabola through each consecutive triple of points and integrating it exactly. It achieves fourth-order accuracy, far better than the trapezoid rule, and is exact for any polynomial up to degree three.

Formula

On an even number of equal panels of width h, the integral is (h/3) times [f0 + 4(f1+f3+...) + 2(f2+f4+...) + fn]. The alternating weights 4 and 2 come from integrating the fitted parabolas. We integrate sin(x) from 0 to pi, whose exact value is 2.

python

import numpy as np
f=np.sin; a,b,n=0,np.pi,8
x=np.linspace(a,b,n+1); h=(b-a)/n
y=f(x)
I=h/3*(y[0]+y[-1]+4*y[1:-1:2].sum()+2*y[2:-1:2].sum())
print('Simpson',round(I,8),'exact 2, error',round(abs(I-2),3e-1*0+8))

Result

With just eight panels Simpson's rule returns 2.0000 to five or six digits, an error near 1e-5, whereas the trapezoid rule with the same points would be off by around 1e-2. Because the error scales as h^4, doubling the panel count cuts the error by roughly sixteen. Simpson requires an even panel count; for smooth integrands it is an excellent default.