% Compare integration rules
close all;
f = @(x) exp(x); a=0;b=1;
% f = @(x) sin(x); a=0;b=pi;
% f = @(x) exp(-x.^2); a=-5;b=5;
% f = @(x) x^{pi} .* sin(x.^2 +cos(x)); a=1;b=2;
I=integral(f,0,1);
steps=10:10:200;
for n=steps
     t=[a:(b-a)/n:b];
     leftpts=t(1:end-1);
     rightpts=t(2:end);
     midpts=(leftpts+rightpts)/2;
     left(n)=(b-a)*sum(f(leftpts))/n;
     right(n)=(b-a)*sum(f(rightpts))/n;
     trap(n)=(left(n)+right(n))/2;
     mid(n)=(b-a)*sum(f(midpts))/n;
     simp(n)=((b-a)/(3*n))*(sum(f(t))+3*sum(f(t(2:2:n)))+sum(f(t(3:2:n-1))) );
end  % for n

figure; hold on; grid on;
title('Approximate integrals for f(x)= exp(x) on [0,1]')
plot(steps,left(steps),'r','LineWidth',3);
plot(steps,right(steps),'g','LineWidth',3);
plot(steps,mid(steps),'b','LineWidth',3);
plot(steps,trap(steps),'c','LineWidth',3);
plot(steps,simp(steps),'k','LineWidth',3);
legend('Left', 'Right','Midpoint','Trapezoid','Simpson')

figure; hold on; grid on;
title('Errors for f(x)= exp(x) on [0,1]')
plot(steps,left(steps)-I,'r','LineWidth',3);
plot(steps,right(steps)-I,'g','LineWidth',3);
plot(steps,mid(steps)-I,'b','LineWidth',3);
plot(steps,trap(steps)-I,'c','LineWidth',3);
plot(steps,simp(steps)-I,'k','LineWidth',3);
legend('Left', 'Right','Midpoint','Trapezoid','Simpson')

figure; hold on; grid on;
title('Log base 10 of errors for f(x)= exp(x) on [0,1]')
plot(steps,log10(abs(left(steps)-I)),'r','LineWidth',3);
plot(steps,log10(abs(right(steps)-I)),'g','LineWidth',3);
plot(steps,log10(abs(mid(steps)-I)),'b','LineWidth',3);
plot(steps,log10(abs(trap(steps)-I)),'c','LineWidth',3);
plot(steps,log10(abs(simp(steps)-I)),'k','LineWidth',3);
legend('Left', 'Right','Midpoint','Trapezoid','Simpson')

I