% Chapter 9, Section 9.1. 
% f(x) = sin x. Approximate f'(pi/3)   

% 1. Forward-difference formula approximation and error
f = inline('(sin(pi/3+h)-sin(pi/3))/h');
for i=1:16
    h(i) = 10^-i;
    fh(i) = f(h(i));
    err(i) = abs(0.5 - fh(i));
end;
fprintf('Using forward-difference formula:\n');
fprintf('   h      (sin(pi/3+h)-sin(pi/3))/h      error\n');
for i=1:16
    fprintf('%7.1e %24.15e        %9.1e \n', h(i), fh(i),err(i));
end
figure(1)
loglog(h,err);
xlabel('log h'); 
ylabel('log error');
title('Error in the forward-difference approximation')


% 2. Centered-difference formula approximation and error
f = inline('(sin(pi/3+h)-sin(pi/3-h))/(2*h)');
for i=1:16
    h(i) = 10^-i;
    fh(i) = f(h(i));
    err(i) = abs(0.5 - fh(i));
end
fprintf('\n');
fprintf('Using forward-difference formula:\n');
fprintf('   h       (sin(pi/3+h)-sin(pi/3+h))/(2h)             error\n');
for i=1:16
    fprintf('%7.1e      %24.15e              %9.1e \n', h(i), fh(i),err(i));
end
figure(2);
loglog(h,err);
xlabel('log h'); 
ylabel('log error');
title('Error in the centered-difference approximation')