%
% Trapezoid Method for int(2xe^(-0.2x))dx;
% Finds the best h and n for given tolerance
%

f  = inline('2*x*exp(-0.2*x)');

n = 1;

%%%%%

a = 0;
b = 10;
actual = 50 - 150*exp(-2);

tol      = 10^(-5);
MAX_ITER = 2000;

fprintf('------------------------------------------------\n');
fprintf('  n              h           sum          error \n');
fprintf('------------------------------------------------\n');
while( n < (MAX_ITER+1) )
    h = (b-a)/n;
    sum = h*(f(a)+f(b))/2;
    if(n==1)
        dx = abs(sum-actual);
        fprintf('%3d   %8.6e   % 12.6f % 12.6e\n',n, h, sum, dx);
    else
        for j = 1:(n-1)
            x = a+j*h;
            sum = sum + h*f(x);
        end
        dx = abs(sum-actual);
        fprintf('%3d   %8.6e   % 12.6f % 12.6e\n',n, h, sum, dx);
    end   
    if( dx<tol ) 
        return;
    end
    n = n+1;
end
fprintf('WARNING: Trapezoid method did not converge after %d steps.\n',n);



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
