Lesson 11 of 18

Trapezoidal Rule

Trapezoidal Rule

Instead of rectangles, use trapezoids — connect adjacent points with line segments:

h2[f(a)+2f(a+h)+2f(a+2h)++2f(bh)+f(b)]\frac{h}{2} \cdot \left[f(a) + 2f(a+h) + 2f(a+2h) + \cdots + 2f(b-h) + f(b)\right]

where h=banh = \frac{b-a}{n}.

Derivation

Each trapezoid has two parallel sides f(xi)f(x_i) and f(xi+1)f(x_{i+1}) and width hh. Its area is h(f(xi)+f(xi+1))2\frac{h \cdot (f(x_i) + f(x_{i+1}))}{2}. Sum all nn trapezoids — the interior points appear twice:

Area=h2[f(x0)+2f(x1)+2f(x2)++2f(xn1)+f(xn)]\text{Area} = \frac{h}{2} \cdot \left[f(x_0) + 2f(x_1) + 2f(x_2) + \cdots + 2f(x_{n-1}) + f(x_n)\right]

Accuracy

Error is O(h2)O(h^2) — halving nn reduces error by factor of 4. The trapezoidal rule is exact for linear functions.

Error Formula

Error(ba)312n2maxf(x)\text{Error} \leq \frac{(b-a)^3}{12n^2} \cdot \max|f''(x)|

For f(x)=sin(x)f(x) = \sin(x), maxf=1\max|f''| = 1, so on [0,π][0, \pi] with n=100n=100: error π31200000.000258\leq \frac{\pi^3}{120000} \approx 0.000258.

Comparison

RuleError orderExact for
Left/RightO(h)O(h)Constants
TrapezoidO(h2)O(h^2)Linear
SimpsonO(h4)O(h^4)Cubic

Your Task

Implement double trapezoid(double (*f)(double), double a, double b, int n).

TCC compiler loading...
Loading...
Click "Run" to execute your code.