%we try to find the derivative of sin(x) at x=1. 
%of course, that derivative is cos(1). so first, we store that
%value
h=input('the initial value of h is:  ');
i=input('the initial value of i is (choose i=0):   ');
%requires h=1 and i=0 initialization
rightval=cos(1);
for i=1:10
  h=h/10;
  %we now try three different ways to compute the derivative numerically

  %first, by using sin(1+h) and sin(1)
  df1=(sin(1+h)-sin(1))/h;
  e(i,1)=df1-rightval;

  %second, by using sin(1+h) and sin(1-h)
  df2=(sin(1+h)-sin(1-h))/(2*h);
  e(i,2)=df2-rightval;

  %third, by extrapolation. the rule should be 
  %df3=(4*df2(h)-df2(2h))/3

  df2h=(sin(1+2*h)-sin(1-2*h))/(4*h);
  df3=(4*df2-df2h)/3;
  e(i,3)=df3-rightval;

  format long
  h
  disp('current errors are')
  e(i,:)
     if i>1, 
     disp('The ratios between current and previous error')
	 r=e(i,:)./e(i-1,:), end
  disp('                                               ')
  disp('+++++++++++++++++++++++++++++++++++++++++++++++')
  pause
end

%now, we compute the smallest error that each of the methods was
%able to achieve (each on of them achieved that at a different h level, though)
disp('the minimal error achieved for each of the methods is')

minerror=min(abs(e))
%the above command is equivalent to the following 4-line code
%  for j=1:3
%    minerror(j)=min(abs((e(:,j))));
%  end
%  minerror


