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);
