% Example showing how to compute approximations to the first derivative
%
% Input Data
%    Text Example 2 for f(x) = x e^x
%
x=[1.8 1.9 2.0 2.1 2.2];
f=[10.889365 12.703199 14.778112 17.148957 19.855030];
h=0.1;
N=length(x);
exactF=x.*exp(x);
exactdF=x.*exp(x)+exp(x);

% Two-Point Formulae
for i=1:N-1
   TwoPt_Forward(i) = (f(i+1)-f(i))/h;
end
Error_Forward=abs(TwoPt_Forward-exactdF(1:N-1));
for i=2:N
   TwoPt_Backward(i-1) = (f(i)-f(i-1))/h;
end
Error_Backward=abs(TwoPt_Backward-exactdF(2:N));

disp('Two Point Results: Forward and Backward Diff.')
disp('  x-value   Approx.      Error')
disp([x(1:N-1)', TwoPt_Forward', Error_Forward' ])
disp([x(2:N)', TwoPt_Backward', Error_Backward' ])

% Three-Point Formulae
for i=1:N-2
   ThreePt_Forward(i) = (-3*f(i)+4*f(i+1)-f(i+2))/(2*h);
end
Error_For_3pt=abs(ThreePt_Forward-exactdF(1:N-2));
for i=2:N-1
   Central(i-1) = (f(i+1)-f(i-1))/(2*h);
end
Error_Central=abs(Central-exactdF(2:N-1));
for i=3:N
   ThreePt_Backward(i-2) = (3*f(i)-4*f(i-1)+f(i-2))/(2*h);
end
Error_Back_3pt=abs(ThreePt_Backward-exactdF(3:N));

disp('Three Point Results: Forward, Central Diff. and Backward')
disp('  x-value   Approx.      Error')
disp([x(1:N-2)', ThreePt_Forward', Error_For_3pt' ])
disp([x(2:N-1)', Central', Error_Central' ])
disp([x(3:N)', ThreePt_Backward', Error_Back_3pt' ])

% Five-Point Formulae
for i=3:N-2
   FivePt_Central(i-2) = (f(i-2)-8*f(i-1)+8*f(i+1)-f(i+2))/(12*h);
end
Error_Central_5pt=abs(FivePt_Central-exactdF(3:N-2));
for i=1:N-4
   FivePt_Forward(i) = (-25*f(i)+48*f(i+1)-36*f(i+2)+16*f(i+3)-3*f(i+4))/(12*h);
end
Error_For_5pt=abs(FivePt_Forward-exactdF(1:N-4));

disp('Five Point Results: Central Diff. and Forward')
disp('  x-value   Approx.      Error')
disp([x(3:N-2)', FivePt_Central', Error_Central_5pt' ])
disp([x(1:N-4)', FivePt_Forward', Error_For_5pt' ])

