% Demonstrate Effectiveness of different methods in
% Chapter 3 of Burden & Faires, 8th Edition.
%
% Written by Ming Gu for Math 128A, Fall 2008
%
%f  = inline('1./sqrt(1+x.^2)','x');
%df = inline('-x./((1+x.^2).^(3/2))','x');
f  = inline('1./(1+x.^2)','x');
df = inline('-2*x./((1+x.^2).^(2))','x');
L  = -2;
U  = 2;
nn = 200;
fig= 1;
for m = 5:10:25
    n = 2 * m;
%
% we do equi-spaced interpolation & approximation.
%
    x    = L + (U-L)/(n-1)*(0:n-1)';
    fx   = f(x);
    dfx  = df(x);
    NDD  = NewtonDividedDifference(x,fx);
    NDD2 = NewtonDividedDifference2(x,fx,dfx);
    dfx2 = [dfx(1);dfx(n)];
    Spls = ClampedSplines(x,fx,dfx2);
    xnew = sort((L+U)/2+(U-L)/2*rand(nn,1).*sign(randn(nn,1)),'ascend');
    fxnew= f(xnew);
    fNDD = EvaluateNDD(xnew,x,NDD);
    fNDD2= EvaluateNDD2(xnew,x,NDD2);
    fSpls= EvaluateClampedSplines(xnew,x,Spls);
%
% display results
%
    figure(fig);
    clf;
    hold on;
    plot(xnew,fxnew,'k-');
    plot(xnew,fNDD,'r-.');
    plot(xnew,fNDD2,'b:');
    plot(xnew,fSpls,'y--');
    legend('TrueValue','Interpolation','Hermite','Clamped Splines','Location','NorthEast');
    ff = ['Interpolations & Approximations with ', num2str(n), ' nodes'];
    title(ff,'Fontsize',18);
    fig = fig + 1;
    figure(fig);
    clf;
    hold on;
    semilogy(xnew,abs(fNDD-fxnew),'r-.');
    ff = ['Errors with Interpolation ', num2str(n), ' nodes'];
    title(ff,'Fontsize',18);
    fig = fig + 1;
    figure(fig);
    clf;
    hold on;
    semilogy(xnew,abs(fNDD2-fxnew),'b:');
    ff = ['Errors with Hermite ', num2str(n), ' nodes'];
    title(ff,'Fontsize',18);
    fig = fig + 1;
    figure(fig);
    clf;
    hold on;
    semilogy(xnew,abs(fSpls-fxnew),'y--');
    ff = ['Errors with Clamped Splines ', num2str(n), ' nodes'];
    title(ff,'Fontsize',18);
end













  
