%a script to plot interpolation error of lagrange polynomials on [-1,1]
%Brad Nelson 1/22/11

%functions to explore...
f1=@(x) sin(2*exp(x));
f2=@(x) (1+25*x.^2).^(-1);

n=25; %number of points
%xj=set of chebychev points on [-1,1]
xj=zeros(1,n);
for i=1:n
   xj(i)=-cos(pi*(i-1)/(n-1)); 
end
xs=-1:0.002:1; %set of xs to plot over

%lagrange polynomials for f1 and f2
p1=zeros(1,numel(xs));
p2=zeros(1,numel(xs));

for i=1:numel(xs);
p1(i) = f1(xj)*lagrange(xs(i),xj);
p2(i) = f2(xj)*lagrange(xs(i),xj);
end

%interpolation error for p1 and p2
es= [f1(xs)-p1;f2(xs)-p2];

%plots error for first function
figure;
plot(xs,es(1,:),'-');
title('interpolation error for sin(2e^x)');
print -depsc interperrf1_cheby.eps;

%plots error for second function
figure;
plot(xs,es(2,:),'-');
title('interpolation error for (1+25*x^2)^{-1}');
print -depsc interperrf2_cheby.eps;

%------------------------------------------------
%now to graph max interpolation error as function of n for f1

maxs=zeros(1,40);
for n=1:40;
   %xj=set of chebychev points on [-1,1]
    xj=zeros(1,n);
    for i=1:n
     xj(i)=-cos(pi*(i-1)/(n-1)); 
    end
   for i=1:numel(xs);
        p1(i) = f1(xj)*lagrange(xs(i),xj);
   end
   es=f1(xs)-p1;
   maxs(n)=max(abs(es));
end
figure;
semilogy(1:40,maxs,'.-');
title('interpolation error as function of n points');
print -depsc interperrn_cheby.eps

%now to graph max interpolation error as function of n for f2
for n=1:100;
   %xj=set of chebychev points on [-1,1]
    xj=zeros(1,n);
    for i=1:n
     xj(i)=-cos(pi*(i-1)/(n-1)); 
    end
   for i=1:numel(xs);
        p2(i) = f2(xj)*lagrange(xs(i),xj);
   end
   es=f2(xs)-p2;
   maxs(n)=max(abs(es));
end
figure;
semilogy(1:100,maxs,'.-');
title('interpolation error as function of n points');
print -depsc interperrn_cheby2.eps
