% cs3734s04HW10.m
% 4th order finite difference formula for the first derivative
% of the sine function at x=1.

clear all; format long e;
fcn='sin'; 
x = 1; fpExact = cos(x);
h = 0.5;
q = 2;
r = 4;  % order of first error term
fp1 = derivative1c4('sin',x,h);
err1 = fp1-fpExact,
h = h/q;
fp2 = derivative1c4('sin',x,h);
err2 = fp2-fpExact,
abs(err1/err2),  % should be close to 16

% Perform Richardson extrapolation
 
p = 4;  % make sure to change it to 4 (4th order) 
itMax = 10;   % best result is itMax = 10
h = 0.50; T(1,1) = derivative1c4(fcn,x,h);
h = 0.25; T(2,1) = derivative1c4(fcn,x,h);
q = 2;
qp = q^p;
T(2,2) = (qp*T(2,1)-T(1,1))/(qp-1);

for k = 2:itMax
    n = 2^k; h= 0.5/n;
    T(k+1,1) = derivative1c4(fcn,x,h);
    for j = 2:k+1
        c = 2^(j-1);
        T(k+1,j) = (c*T(k+1,j-1)-T(k,j-1))/(c-1);
    end
end
I=T, 

error = I(end,end)-fpExact,

