%
% riemann_ex1.m 
%  Demonstration of convergence rate of simple Riemann sum
%  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; 
fprintf('exact integral = %e\n \n',Iexact);

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

% loop over different interval sizes and output the errors
%
fprintf('N     Abs Error     Rel Error\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
  
  Sn = dx*sum( f(x) );      % compute the Riemann sum
  
  En_abs = abs(Sn-Iexact);  % absolute error
  En_rel = En_abs/Iexact;   % relative error
    
  fprintf('%4i  %e  %e \n',N(k),En_abs,En_rel); 
  
end


