function fig5_5

ns=[4 16 64]; n=1000;
% ns=[40 100 200]; n=2000;
%ns=[400 800 2000]; n=10000;

a=-1; b=1;
x=linspace(a,b,n);

% exact
for ie=1:n
    ye(ie)=1/(1+25*x(ie)^2);
end

% ns(1)
nx=ns(1)+1;
xd=linspace(a,b,nx);
%xd=sort(2*rand(1,nx)-1);
for ix=1:nx
    yd(ix)=1/(1+25*xd(ix)^2);
end
for ii=1:n
    p(ii)=0;
    for k=1:nx
        p(ii)=p(ii)+yd(k)*ell(k,x(ii),xd);
    end
end
max(abs(p))

% ns(2)
nx=ns(2)+1;
xd=linspace(a,b,nx);
%xd=sort(2*rand(1,nx)-1);
for ix=1:nx
    yd(ix)=1/(1+25*xd(ix)^2);
end
for ii=1:n
    pp(ii)=0;
    for k=1:nx
        pp(ii)=pp(ii)+yd(k)*ell(k,x(ii),xd);
    end
end

max(abs(pp))

% ns(3)
nx=ns(3)+1;
xd=linspace(a,b,nx);
%xd=sort(2*rand(1,nx)-1);
for ix=1:nx
    yd(ix)=1/(1+25*xd(ix)^2);
end
for ii=1:n
    ppp(ii)=0;
    for k=1:nx
        ppp(ii)=ppp(ii)+yd(k)*ell(k,x(ii),xd);
    end
end

max(abs(ppp))

clf
% get(gcf)
set(gcf,'Position', [36 1073 580 338])
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)

subaxis(3,1,1,1,'MT',0.005,'MB',0.1,'MR',-0.01,'ML',0.04,'P',0.02)
hold on
box on
plot(x,ye,'r','LineWidth',1.4)
plot(x,p,'--b','LineWidth',1.4)
grid on
%axis([-1 1 -0.5 1.5])
axis([-1 1 -0.5 1.2])
set(gca,'XTick',[-1 0 1])
set(gca,'YTick',[-0.5 1])
legend({' Runge',' n = 4'},'Location','South','FontSize',13,'FontWeight','bold')
set(gca,'FontSize',14,'FontWeight','bold')
hold off

subaxis(3,1,1,2)
hold on
box on
grid on
plot(x,ye,'r','LineWidth',1.4)
plot(x,pp,'--b','LineWidth',1.8)
%axis([-1 1 -0.5 1.5])
axis([-1 1 -15 2])
set(gca,'XTick',[-1 0 1])
set(gca,'YTick',[-15 2])
legend({' Runge',' n = 16'},'Location','South','FontSize',13,'FontWeight','bold')

set(gca,'FontSize',14,'FontWeight','bold')
hold off

subaxis(3,1,1,3)
hold on
box on
grid on
plot(x,ye,'r','LineWidth',1.4)
plot(x,ppp,'--b','LineWidth',1.8)
%axis([-1 1 -0.5 1.5])
axis([-1 1 -15 2])
%set(gca,'YTick',[-4 -3 -2 -1 0 1])
xlabel('x-axis')
set(gca,'XTick',[-1 0 1])
set(gca,'YTick',[-15 2])
legend({' Runge',' n = 64'},'Location','South','FontSize',13,'FontWeight','bold')
set(gca,'FontSize',14,'FontWeight','bold')
hold off

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

% ell_i(x) function
function p=ell(i,x,xd)
[n1 n2]=size(xd);
p=1;
for j=1:n2
    if j ~= i
        p=p*(x-xd(j))/(xd(i)-xd(j));
    end
end






