Section 13.3 Trapezoidal rule
When a function is increasing, the leftpoint rule underestimates its integral, and rightpoint rule overestimates it. So, their average \(T_n=(L_n+R_n)/2\) should be a better approximation. This is the Trapezoidal Rule:
\begin{equation*}
T_n = \frac{h}{2}(f(a)+f(b)) + h( f(x_1)+\dots+f(x_{n-1}))
\end{equation*}
In Matlab, the computation is similar to Example 13.2.1
T = (f(x(1)) + f(x(end))) * h/2 + sum(f(x(2:end-1)))*h;
It may be simpler to compute the vector y = f(x)
first, which reduces the number of calls to function f
and the number of parentheses:
T = (y(1) + y(end)) * h/2 + sum(y(2:end-1))*h;
Example 13.3.1. Comparing the accuracy of four rules.
For the function \(f(x) = e^x \) on the interval \([-1, 1]\text{,}\) use Matlab to compute the left-, right, and midpoint approximations with \(n=10\) and find the error of each approximation (that is, its difference with the actual integral).
Solution
f = @(x) exp(x); a = -1; b = 1; n = 10; h = (b-a)/n; x = a:h:b; y = f(x); L = sum(y(1:end-1))*h; R = sum(y(2:end))*h; T = (y(1) + y(end)) * h/2 + sum(y(2:end-1))*h; midpoints = (x(1:end-1) + x(2:end))/2; M = sum(f(midpoints))*h; exact = exp(1)-exp(-1); er = abs([L R T M] - exact); fprintf('Errors: Leftpoint %g, Rightpoint %g, Trapezoidal %g, Midpoint %g\n', er);
Here fprintf
“unpacks” the vector er
, inserting its entries in the right places.