Trapezoidal rule and Simpson's rule in JavaScript
Advanced · 4 min read
The area under a curve is called its integral, and it shows up everywhere: distance from a speed graph, energy from a power graph, total rainfall from a rate. For many curves there is no neat formula, so programs estimate the area by cutting it into thin strips and adding the strips up. This is numerical integration.
In this tutorial you will write three ways of doing it: the trapezoidal rule, the midpoint rule and Simpson's rule. You will measure how the error shrinks as the strips get thinner, discover that Simpson's rule is just the other two mixed together, and find where adding more strips stops helping. You need to know loops and how to pass a function as an argument.
Strips and trapezoids
Split the range from a to b into n strips of equal width h = (b - a) / n. Over each strip, join the curve's two end points with a straight line. That makes a trapezoid, a four-sided shape with two parallel sides, and its area is the width times the average of the two heights. Add up all the trapezoids and you have an estimate.
Passing a function in
The rules take the curve as a function f, so the same code works for any curve:
const square = (x) => x * x;
const apply = (f, x) => f(x);
console.log(apply(square, 3)); // 9
The exact area under x * x from 0 to 3 is 9, so that is the answer to aim for.
Here is the exercise. Have a go on your own first if you like, then read on and we will build it together.
113 Integrating by the trapezium rule, and Simpson on top
hardIntegrate x² from 0 to 3 by the trapezium rule and show the error quartering as you double the strips. Add the midpoint and Simpson rules, and check that Simpson is exactly the combination of the other two. Then integrate 1/x from 1 to 2, compare against Math.log(2), and find where refining the mesh stops paying.
Stuck? Three hints, smallest first
- 1. The trapezium sum is
h * (f(a)/2 + f(a + h) + ... + f(b)/2), and it overestimates a curve that bends upwards. - 2. Simpson weights the interior points 4, 2, 4, 2, ..., which needs an even number of strips.
- 3. Simpson is
(trapezium + 2 * midpoint) / 3, and also(4 * T(h/2) - T(h)) / 3.
Step 1: the trapezoidal rule
function trapezium(f, a, b, n) {
const h = (b - a) / n;
let total = (f(a) + f(b)) / 2;
for (let i = 1; i < n; i++) total += f(a + i * h);
return total * h;
}
console.log(trapezium(square, 0, 3, 1), trapezium(square, 0, 3, 6)); // 13.5 9.125
Every inside point belongs to two trapezoids, so it counts in full. The two end points belong to only one each, so they count half. Multiply the total by the width h at the end.
One strip gives 13.5 and six give 9.125. Both are too big, because x * x curves upward and a straight line between two points on it sits above the curve.
Step 2: watch the error shrink
console.log([1, 2, 6, 12].map((n) => trapezium(square, 0, 3, n) - 9)); // [ 4.5, 1.125, 0.125, 0.03125 ]
Each time the strips double (1 to 2, 6 to 12), the error is divided by 4. The error depends on the strip width squared, written h². Halve h and you quarter the error.
Step 3: the midpoint rule
Instead of the two ends of each strip, measure the curve once, in the middle, and use that as the height of a rectangle.
function midpoint(f, a, b, n) {
const h = (b - a) / n;
let total = 0;
for (let i = 0; i < n; i++) total += f(a + (i + 0.5) * h);
return total * h;
}
const T = trapezium(square, 0, 3, 6);
const Mid = midpoint(square, 0, 3, 6);
console.log(Mid - 9, T - 9); // -0.0625 0.125
The midpoint rule errs the other way, and by half as much: -0.0625 against +0.125.
Step 4: mix them and the error cancels
If one error is +2 units and the other is -1 unit, then one part of the first plus two parts of the second cancels out:
console.log((T + 2 * Mid) / 3); // 9
Exactly 9. That mix is Simpson's rule.
Step 5: Simpson's rule on its own
Written directly, Simpson's rule weights the points 1, 4, 2, 4, 2, ..., 4, 1 and divides by 3. The 4, 2 pattern needs an even number of strips.
function simpson(f, a, b, n) {
if (n % 2 !== 0) throw new RangeError('Simpson needs an even number of strips');
const h = (b - a) / n;
let total = f(a) + f(b);
for (let i = 1; i < n; i++) total += f(a + i * h) * (i % 2 ? 4 : 2);
return (total * h) / 3;
}
const cube = (x) => x ** 3;
console.log(simpson(square, 0, 3, 2), simpson(cube, 0, 2, 2)); // 9 4
With just two strips it is exact for x² and even for x³ (whose exact area from 0 to 2 is 4). An odd strip count throws a RangeError.
Step 6: a curve with no easy answer
The area under 1 / x from 1 to 2 is the natural log of 2, which Math.log(2) gives as 0.6931471805599453.
const reciprocal = (x) => 1 / x;
const s20 = simpson(reciprocal, 1, 2, 20);
console.log(trapezium(reciprocal, 1, 2, 20), s20); // 0.693303381792694 0.6931473746651161
let crossover = 0;
for (let n = 2; n <= 600 && crossover === 0; n++) {
if (Math.abs(trapezium(reciprocal, 1, 2, n) - Math.log(2)) <= Math.abs(s20 - Math.log(2))) crossover = n;
}
console.log(crossover); // 568
The loop searches for the number of trapezoid strips needed to be as accurate as Simpson with 20. It takes 568. Simpson's error depends on h to the fourth power, so it pulls further ahead the more accuracy you want.
Step 7: the wrong turn, comparing with ===
Mixing two trapezoidal estimates, (4 * T(h/2) - T(h)) / 3, is mathematically the same as Simpson. It is called Richardson extrapolation.
const t10 = trapezium(reciprocal, 1, 2, 10);
const t20 = trapezium(reciprocal, 1, 2, 20);
const richardson = (4 * t20 - t10) / 3;
console.log(richardson, richardson === s20); // 0.693147374665116 false
The two numbers differ in the last digit, because the same math is done in a different order and rounds differently. Compare results like these with a small tolerance, never with ===.
Step 8: more strips stop helping
const ratios = [];
let previous = 0;
for (const n of [100, 1000, 10000, 100000]) {
const error = Math.abs(trapezium(reciprocal, 1, 2, n) - Math.log(2));
if (previous !== 0) ratios.push(previous / error);
previous = error;
}
console.log(ratios.map((r) => Math.round(r * 1e4) / 1e4)); // [ 99.9988, 100.0001, 100.1778 ]
Ten times as many strips should make the error 100 times smaller (10 squared). That holds up to 10000 strips. At 100000 the ratio drifts to 100.18, because a hundred thousand rounded additions now add error of their own. Choose a better rule rather than ever more strips.
The full solution
The answer panel has all three rules and every case above. It also tries 1 / Math.sqrt(x) from 0 to 1, where the trapezoidal rule hits the infinite value at 0 and returns Infinity, while the midpoint rule never touches the end and heads slowly toward the true answer, 2. Press Run to see the output.
function trapezium(f, a, b, n) {
const h = (b - a) / n;
let total = (f(a) + f(b)) / 2;
for (let i = 1; i < n; i++) total += f(a + i * h);
return total * h;
}
function midpoint(f, a, b, n) {
const h = (b - a) / n;
let total = 0;
for (let i = 0; i < n; i++) total += f(a + (i + 0.5) * h);
return total * h;
}
function simpson(f, a, b, n) {
if (n % 2 !== 0) throw new RangeError('Simpson needs an even number of strips');
const h = (b - a) / n;
let total = f(a) + f(b);
for (let i = 1; i < n; i++) total += f(a + i * h) * (i % 2 ? 4 : 2);
return (total * h) / 3;
}
const square = (x) => x * x;
const cube = (x) => x ** 3;
const line = (x) => 2 * x + 1;
const reciprocal = (x) => 1 / x;
const spike = (x) => 1 / Math.sqrt(x); // infinite at x = 0
const trapErrors = [1, 2, 6, 12].map((n) => trapezium(square, 0, 3, n) - 9);
const T = trapezium(square, 0, 3, 6);
const Mid = midpoint(square, 0, 3, 6);
const t10 = trapezium(reciprocal, 1, 2, 10);
const t20 = trapezium(reciprocal, 1, 2, 20);
const s20 = simpson(reciprocal, 1, 2, 20);
const richardson = (4 * t20 - t10) / 3;
const halvingRatio = (t10 - Math.log(2)) / (t20 - Math.log(2));
// How many trapezium strips does it take to match Simpson's twenty?
let crossover = 0;
for (let n = 2; n <= 600 && crossover === 0; n++) {
if (Math.abs(trapezium(reciprocal, 1, 2, n) - Math.log(2)) <= Math.abs(s20 - Math.log(2))) crossover = n;
}
// Keep refining and watch the tenfold gain in accuracy decay.
const ratios = [];
let previous = 0;
for (const n of [100, 1000, 10000, 100000]) {
const error = Math.abs(trapezium(reciprocal, 1, 2, n) - Math.log(2));
if (previous !== 0) ratios.push(previous / error);
previous = error;
}
let oddStrips = 'no error';
try { simpson(square, 0, 3, 3); } catch (error) { oddStrips = error.constructor.name; }
console.log('x2 trapezium :', [1, 2, 6, 12].map((n) => trapezium(square, 0, 3, n)), 'exact 9');
console.log('errors :', trapErrors, '<- each a quarter of the last');
console.log('midpoint :', Mid, 'trapezium', T, '(T + 2M) / 3 =', (T + 2 * Mid) / 3);
console.log('Simpson x2, x3:', simpson(square, 0, 3, 2), simpson(cube, 0, 2, 2), 'exact 9 and 4');
console.log('a straight line:', trapezium(line, 0, 4, 1), trapezium(line, 0, 4, 7), trapezium(line, 0, 4, 8));
console.log('1/x, ln 2 :', t10, t20, s20, Math.log(2));
console.log('richardson :', richardson, 'against Simpson', s20, 'gap', richardson - s20);
console.log('halving ratio :', halvingRatio, 'refinement ratios', ratios);
console.log('crossover :', crossover, 'trapezium strips to match Simpson on 20');
console.log('spike :', trapezium(spike, 0, 1, 100), 'midpoint', midpoint(spike, 0, 1, 100), 'exact 2');
console.log('odd strips :', oddStrips);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('one trapezium over x2 gives 13.5, and six give 9.125: always an overestimate', [trapezium(square, 0, 3, 1), T], [13.5, 9.125]);
test('doubling the strips quarters the error, exactly, for a quadratic', trapErrors, [4.5, 1.125, 0.125, 0.03125]);
test('the midpoint rule errs half as much, the other way, and Simpson is (T + 2M) / 3', [Mid - 9, (T + 2 * Mid) / 3], [-0.0625, 9]);
test('Simpson is exact for a quadratic and for a cubic, on two strips', [simpson(square, 0, 3, 2), simpson(cube, 0, 2, 2), oddStrips], [9, 4, 'RangeError']);
test('the trapezium rule is exact for a straight line, but the arithmetic is not always', [trapezium(line, 0, 4, 1), trapezium(line, 0, 4, 8), trapezium(line, 0, 4, 7)], [20, 20, 19.999999999999996]);
test('over 1/x the trapezium error falls by four when the strips double', [t10, t20, Math.abs(halvingRatio - 4) < 0.01], [0.693771403175428, 0.693303381792694, true]);
test('Simpson on 20 strips is worth 568 trapezium strips: 21 evaluations against 569', [crossover, Math.abs(s20 - Math.log(2)) < 2e-7], [568, true]);
test('Richardson on two trapezium sums IS Simpson, to within a single bit', [richardson, s20, richardson === s20, Math.abs(richardson - s20) < 2e-16], [0.693147374665116, 0.6931473746651161, false, true]);
test('but tenfold refinement stops buying a hundredfold accuracy at 100000 strips', [ratios.map((r) => Math.round(r * 1e4) / 1e4), ratios[2] > 100.1], [[99.9988, 100.0001, 100.1778], true]);
The trapezium rule is a sum with two half-weights at the ends, and its error is proportional to h², which the first two assertions show directly: 4.5, 1.125, 0.125, 0.03125 as the strips go 1, 2, 6, 12. Every one is an overestimate, because x² bends upwards and a chord sits above the curve. The midpoint rule makes the opposite error at half the size — -0.0625 against 0.125 — which is exactly why (T + 2M) / 3 lands on 9 with nothing left over. That combination is Simpson's rule, and the same rule written as (4 T(h/2) - T(h)) / 3 is Richardson extrapolation: two cheap estimates of a bad method make one estimate of a much better one.
Simpson is exact for cubics as well as quadratics, which is the free lunch that makes it the default. On 1/x over [1, 2] its 20-strip answer takes the trapezium rule 568 strips to equal — 21 function evaluations against 569, and the gap widens as you ask for more accuracy, because one method improves like h² and the other like h⁴. Note the assertion about Richardson: it produces 0.693147374665116 where simpson produces 0.6931473746651161. The same number mathematically, one bit apart in doubles, because the operations happen in a different order. Comparing two implementations of the same formula with === is a test that fails for no reason.
The last two assertions are the discipline. Refinement is not free and does not continue to pay: from n = 100 to n = 10000 each tenfold refinement gives back very close to the promised factor of 100, and at n = 100000 the ratio is 100.18 instead of 100, because a hundred thousand rounded additions have begun to contribute their own error. Push further and the error starts to grow. Use a better rule rather than a finer mesh. And the spike shows the other failure mode: 1 / Math.sqrt(x) has a finite integral over [0, 1], but the trapezium rule evaluates the endpoint and returns Infinity, where the midpoint rule never touches it and converges — slowly — to 2.
Common mistakes
- Counting the end points in full. In the trapezoidal rule they get half weight.
- Giving Simpson an odd number of strips. The 4, 2, 4 pattern breaks, which is why the function throws.
- Adding strips forever. Past a point, rounding error grows faster than the method improves.
Try it yourself
- Integrate
Math.sinfrom 0 toMath.PIwith each rule. The exact answer is 2. - Find how many midpoint strips match Simpson with 20 strips on
1 / x. - Integrate a straight line,
(x) => 2 * x + 1, from 0 to 4 with the trapezoidal rule on 1, 7 and 8 strips. Why is it exact in theory, and what does 7 strips print?