%
% riemann_ex2.m
% Compare the convergence rate of Riemann sums using left endponts and
% using midpoints of the intervals
%
% applied to the integral of f(x)=x*exp(-400*x^2)
%

% function handle to integrand
%
f=@(x)(x.*exp(-400*x.^2));

% integration interval
%
x0 = 0; % left endpoint
x1 = 0.1; % right endpoint

% exact integral
%
Iexact = (1-exp(-4))/800;

% array of number of subintervals
%
N = 2.^(4:10);

% loop over different interval sizes and output the errors
%
fprintf('N left point mid point\n');
for k=1:length(N)
dx = (x1-x0)/N(k); % interval size
x = (0:(N(k)-1))*dx; % left end points of the intervals
xc = x + 0.5*dx; % midpoints

% compute Riemann sums
%
Sn = dx*sum( f(x) );
Snc = dx*sum( f(xc) );

% compute the errors and store them
%
En(k) = abs((Sn -Iexact)/Iexact);
Enc(k) = abs((Snc-Iexact)/Iexact);

% output the results
%
fprintf('%4i %e %e \n',N(k),En(k),Enc(k));

end

% make a log-log plot of the results
%
hp=loglog(N,En,'o-',N,Enc,'s-');
set(hp,'linewidth',3,'markersize',10);
set(gca,'fontsize',14);
xlabel('number of intervals');
ylabel('relative errors');
legend('left points','midpoints');