function fig6_3

%  this includes Fig 6.3, Table 6.1, and Fig 6.4

%  Integrate  f(x)  over  [a, b]  using midpoint rule
%
%  Inputs:
%        a = left endpoint of interval
%        b = right endpoint of interval
%        n = number of subintervals
%

a=0; b=1;

exact=(exp(3)-1)/3;
n=40;
interv=[500 1000 2000 4000 8000 16000 32000 64000];
nk=length(interv);
for k=1:nk
    n=interv(k);
    tic
    M(k)=midpt(a,b,n);
    toc
    err(k)=abs(exact-M(k));
end

% table 6.1
fprintf('\n RIE = relative iterative error \n\n')
fprintf(' k \t  n  \t\t I_M \t \t Error \t\t RIE \n')
for k=1:nk
    if k==1
        fprintf(' %i \t %i\t %19.15f \t %5.1e  \n',1,interv(k),M(k),err(k))
        %fprintf('\\, %i \\, & \\, %i \\, & \\,\\, %19.15f \\,\\, & \\,\\, %5.1e  \\,\\, & \\,\\,  \\\\ \n',1,interv(k),M(k),err(k))
    else
        R(k-1)=abs((M(k)-M(k-1))/M(k));
        fprintf(' %i \t %i \t %19.15f \t %5.1e  \t %5.1e   \n',k,interv(k),M(k),err(k),R(k-1))
        %fprintf('\\, %i \\, & \\, %i \\, & \\,\\, %19.15f \\,\\, & \\,\\, %5.1e  \\,\\, & \\,\\, %5.1e  \\\\ \n',k,interv(k),M(k),err(k),R(k-1))
    end
end
fprintf('\n')

% fig 6.3
figure(1)
clf
% get(gcf)
set(gcf,'Position', [25 1115 658 230])
subaxis(1,1,1,1,'MT',0.01,'MB',0.18,'MR',-0.02,'ML',0.03,'P',0.04)
co = [0 0 1;
    0 0.5 0;
    1 0 0;
    0 0.75 0.75;
    0.75 0 0.75;
    0.75 0.75 0;
    0.25 0.25 0.25];
set(groot,'defaultAxesColorOrder',co)

hold on

n=3;
xd=linspace(a,b,n+1);
h=xd(2)-xd(1);
for in=1:n
    plot([xd(in) xd(in+1)], [f(xd(in)+0.5*h) f(xd(in)+0.5*h)],'--r','LineWidth',2)
    plot([xd(in) xd(in)], [0 f(xd(in)+0.5*h)],'--r','LineWidth',2)
end
plot([b b], [0 f(xd(n)+0.5*h)],'--r','LineWidth',2)

nx=100;
x=linspace(a,b,nx);
for ix=1:nx
    y(ix)=f(x(ix));
end

plot(x,y,'LineWidth',1.6)
box on
%grid on
xlabel('x-axis')
ylabel('y-axis')
axis([0 1 0 20])
set(gca,'XTick',[0 1/6 1/3 1/2 2/3 5/6 1])
set(gca,'XTickLabel',{'0','1/6','1/3','1/2','2/3','5/6','1'})
%set(gca,'YMinorGrid','off');
set(gca,'FontSize',16,'FontWeight','bold')

%exportgraphics(gcf,'/Users/mark/Desktop/expM.eps')

% fig 6.4
figure(2)
clf
% get(gcf)
set(gcf,'Position', [25 794 658 230])
subaxis(1,1,1,1,'MT',0.01,'MB',0.18,'MR',-0.02,'ML',0.06,'P',0.04)
co = [0 0 1;
    0 0.5 0;
    1 0 0;
    0 0.75 0.75;
    0.75 0 0.75;
    0.75 0.75 0;
    0.25 0.25 0.25];
set(groot,'defaultAxesColorOrder',co)

loglog(interv,err,'--ob','MarkerSize',8,'LineWidth',1.6)
hold on
loglog(interv(2:nk),R,'--*r','MarkerSize',8,'LineWidth',1.6)
grid on
axis([1e3 1e5 1e-10 1e-5])
set(gca,'ytick',[1e-10 1e-9 1e-8 1e-7 1e-6 1e-5])
xlabel('n-axis')
ylabel('Error')
legend({' Error',' RIE'},'Location','NorthEast','FontSize',16,'FontWeight','bold')
set(gca,'FontSize',16,'FontWeight','bold')

%exportgraphics(gcf,'/Users/mark/Desktop/midpterr.eps')


function y=f(x)
y=exp(3*x);

%%% composite midpoint: n = number of subintervals
function s=midpt(a,b,n)
xd=linspace(a,b,n+1);
h=xd(2)-xd(1);
s=0;
for j=1:n
    s=s+f(xd(j)+0.5*h);
end
s=h*s;












