Numerical differentiation error

% Numerical differentiation error
%Author: Minster
close all
clear all

f = @(xeval) (sin(xeval));
x = pi/3;
fderiv = cos(x);
format long
%forward difference
fprintf(‘ h FD Error\n=====================================================\n’)
h(1) = 0.1 ;
for i = 1:16
fde(i) = ((f(x+h(i)) – f(x))/h(i)) – fderiv;
fprintf (‘%1.17f %1.17f\n’,h(i),fde(i))
h(i+1) = h(i)*0.1;
end
h2=h(1:16);
plot(log10(h2),log10(abs(fde)))
title(‘Forward Difference Error: log(h) vs. log(error)’)
xlabel(‘log(h)’); ylabel(‘log(error)’)
%break

%central difference
fprintf(‘ h CD Error\n=====================================================\n’)
%central difference
hc(1) = 0.1 ;
for i = 1:16
fdec(i) = ((f(x+hc(i)) – f(x – hc(i)))/(2*hc(i))) – fderiv;
fprintf (‘%1.17f %1.17f\n’,hc(i),fdec(i))
hc(i+1) = hc(i)*0.1;
end
h2c=hc(1:16);
figure(2)
plot(log10(h2c),log10(abs(fdec)))
title(‘Central Difference Error: log(h) vs. log(error)’)
xlabel(‘log(h)’); ylabel(‘log(error)’)