%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Truncation error vs. roundoff error example:
%%    f'(x) approximated by (f(x+h)-f(x))/h
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%clear all; %clear the workspace

n = 20; %number of steps
x = 1; %base value
h = 10; %starting mesh size
M = 1; %estimated maximum value of f''(x).

for i=1:n %loop starts
    
  hh(i) = 0.1*h; h = hh(i); %decrease mesh size
  y = (sin(x+h)-sin(x))/(h);  %compute finite difference approximation
  %y = (sin(x+h)-sin(x-h))/(2*h);  %compute finite difference approximation
  error(i) = abs(cos(x)-y); %compute the absolute error
  error1(i) = h*M/2;   %compute the bound for truncation error
  error2(i) = 2*eps/h; %compute approximate roundoff error  
  
end % loop ends

%output the error vector
error 

figure(1); %open a figure to display results (assign index 1 to this figure)
hold on; %to plot results on top of each other
plot(log10(hh),log10(error),'bs-',log10(hh),log10(error1),'r.-',...
     log10(hh),log10(error2),'k.-'); %plot results in log-log scale
 
legend('total error','truncation','rounding'); %produce graph legend
