fprintf('\n HW 11, Problems 2-3: Comparison of integration methods');
fprintf('\n Intergal of ln(x) from 1 to 3\n\n');
fprintf('  N  |     Midpoing (error)  |    Trapezoid (error)  |   Simpsons (error) \n');
fprintf('---------------------------------------------------------------------------------\n');

a = 1; b = 3;
f = inline('log(x)');
exact = 3*log(3) - 2;
mRange = 1 : 10;

for m = mRange;
    N = 2 ^ m;
    IM(m) = midpoint(a, b, f, N);     Merror(m) = abs(IM(m) - exact);
    IT(m) = trapezoid(a, b, f, N);    Terror(m) = abs(IT(m) - exact);
    IS(m) = simpsons(a, b, f, N);     Serror(m) = abs(IS(m) - exact);
    
    fprintf('%4d | %11.9g (%7.1e) | %11.9g (%7.1e) | %14.12g (%7.1e)\n', ...
            N, IM(m), Merror(m), IT(m), Terror(m), IS(m), Serror(m));
end;
     
subplot(1,2,1);
set(gca, 'fontsize', 14);
plot(mRange, IM, '*-k', mRange, IT, 'o-b', mRange, IS, 'd-r');
legend('Midpoint', 'Trapezoid', 'Simpsons', 'location', 'Best');
title('Comparison of integration methods');
xlabel('m'); ylabel('Integral'); axis tight;

  %%%%%%%%%%%%%%%%%%%%%%%% PROBLEM 3: %%%%%%%%%%%%%%%%%%%%%%%%%

subplot(1,2,2);
set(gca, 'fontsize', 14);
logN = log(2) * mRange;
plot(logN, log(Merror), '*-k', logN, log(Terror), 'o-b', logN, log(Serror), 'd-r');
legend('Midpoint error', 'Trapezoid error', 'Simpsons error', 'location', 'Best');
title('Error behavior: ln |Error| vs. ln N');
xlabel('log(N)'); ylabel('log(Error)'); axis tight;

Mslope = (log(Merror(10)) - log(Merror(9))) / log(2);
Tslope = (log(Terror(10)) - log(Terror(9))) / log(2);
Sslope = (log(Serror(10)) - log(Serror(9))) / log(2);
fprintf('\n\nSlopes: Midpoint=%.2g, Trapezoid: %.2g, Simpsons: %.2g\n', Mslope, Tslope, Sslope);
