%section 4.1 computer problem #2

f = @(x) atan(x);   %f(x) = arctan(x)

%first we interpolate f at 11 points between 1 and 6

x = linspace(1,6,11);    %11 equally spaced points between 1 and 6
c = zeros(1,11);         %coefficients of Newton interpolant

for i=1:11
    c(i) = f(x(i));
end

for j=2:11
    for i=11:-1:j
        c(i) = (c(i)-c(i-1))/(x(i)-x(i-j+1));
    end
end

%now we use our Newton interpolant P, with coefficients c, 
%to extrapolate values of f at 33 points between 0 and 8

x_new = linspace(0,8,33);
z = zeros(1,33);   %z = values of polynomial interpolant on x_new

for i=1:33
    z(i) = c(1);   %inner loop computes z(i) = P(x_new(i))
    p = 1;
    for j=2:11     %recall 11 = # of coefficients in Newton interpolant
        p = p*(x_new(i) - x(j-1));
        z(i) = z(i) + c(j)*p;
    end
end

y_new = zeros(1,33); 

for i=1:33
    y_new(i) = f(x_new(i));   %values of f on x_new
end

plot(x_new,y_new,'-ob',x_new,z,'-xr')
legend('exact values','interpolating curve')

%notice the interpolant is good on [1,6] but less accurate outside [1,6]
