% Finite difference approximation of the first derivative
% using the forward difference formula.
% Illustrate the trade-off between trunction & roundoff errors
% The function used is f(x)=sin(x)
% x = 1     
% h, the step size, varies from 10^-16 to 10^0
% K. Ming Leung, 01/19/03

clear all; hold off; format long;
x = 1; 
h = logspace(-16,-0,200); 
M = 1;
% method 1: use the function name explicitly
% dfApprox = (sin(x+h)-sin(x))./h; % approximate derivative
% method 2: use user-defined function "forwardDiff" to compute f',
% supply the function using a function handle.
%for n=1:200
    dfApprox = forwardDiffF(@sin,x,h);
%end
dfExact = cos(x);                % exact derivative
Err = abs(dfApprox-dfExact);    % error
loglog(h,Err,'x');              % Loglog plot of the error vs h
disp('        h               Error');
disp([h' Err']);
%[minErr, idx]=min(Err);  minh=h(idx); [minh minErr],
title(['Forward Difference formula for first derivative';...
       'Trade-off between Truncation & Roundoff Errors ']);
ylabel('Error','FontSize', 14); xlabel('h','FontSize', 14);
text(5e-5,0.1,'Truncation')
text(5e-5,0.04,'dominated');
text(4e-14,0.1,'Roundoff');
text(4e-14,0.04,'dominated');
axis([1e-17 1e0 1e-10 1e-0]); 
hold on;
plot(h,M*h/2,'r','linewidth',2);
plot(h,2*eps./h,'g','linewidth',2);