%
% 等距节点插值与 Chebyshev 零点插值的比较
%
clear; clc;
f = @(x) 1./(1+x.^2); 
a = -5; b = 5;

n = 30; % 10 次插值
X1 = [ a : (b-a)/n : b ]; % 等距节点
Y1 = f(X1);

X2 = 5*cos([1:2:2*n+1]*pi/(2*n+2)); % Chebyshev 节点
Y2 = f(X2);

x = -5:0.1:5;
yt = f(x);  % 精确值

y1 = zeros(1,length(x)); 
y2 = zeros(1,length(x)); 
for i = 1 : length(x)
    for k = 0 : n
        % 等距插值
        y1(i) = y1(i) + Y1(k+1)*prod(x(i)-X1([1:k,k+2:end]))/prod(X1(k+1)-X1([1:k,k+2:end]));
        % Chebyshev 插值
        y2(i) = y2(i) + Y2(k+1)*prod(x(i)-X2([1:k,k+2:end]))/prod(X2(k+1)-X2([1:k,k+2:end]));
    end
end

plot(x,yt,'r+-',x,y2,'ks-','LineWidth',1);
axis([-5,5,-1,2]);
legend('f(x)','Chebyshev插值')

return
figure(2)
plot(x,y1-yt,'bo-', x,y2-yt,'ks-','LineWidth',1);
legend('等距节点插值','Chebyshev零点插值')
title('误差曲线')

fprintf('n = %d\n', n);
fprintf('等距节点插值误差限: %f\n', norm(y1-yt,inf));
fprintf('Chebyshev零点插值误差限: %f\n', norm(y2-yt,inf));



