% 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;
dfApprox = (sin(x+h)-sin(x))./h; % approximate derivative
dfExact = cos(x);                % exact derivative
Err = abs(dfApprox-dfExact);    % error
loglog(h,Err,'*');              % 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'); xlabel('Step Size, h');
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');
plot(h,2*eps./h,'g');