% illustration of Runge phenomenen

f = @(x) 1./(1+x.^2);
% f=@(x) exp(x);

a = -5;
b = 5;
xVals = -5:0.01:5;
clf


for n=2:20
    % interpolation points
    % equidistant
    x = a+(0:n)*(b-a)/n;
    % Chebyshev
    x = 0.5*(b-a)*cos(pi*(2*(0:n)+1)/(2*n+2));

    coeffs = polyfit(x,f(x),n);

    fVals = polyval(coeffs,xVals);

    plot(xVals,f(xVals),'k','LineWidth',2);
    hold on;
    plot(x,f(x),'ro');
    plot(xVals,fVals,'b','LineWidth',2);
    legend('f(x)','interp. pts','q(x)');
    xlabel('x')
    axis([-5,5,-1,2])
    hold off
    pause
end


