% Script Eg3_1
% Rational Approximation of pi

% Initializations
  M = 1000;
  p_best = 1; q_best = 1; Error = abs(p_best/q_best - pi);
  clc
  disp('    p     q    | p/q  - pi |')
  disp('----------------------------')

% Find the best rational approximation p/q to pi subject to the 
% constraint that both p and q are smaller than M.
  for q=1:ceil(M/pi);
%    Check if there is an improved quotient having denominator q...
     p_minus = floor(q*pi); minusError = abs(p_minus/q - pi);
     if minusError < Error
%       An improved quotient has been discovered...
        p_best = p_minus; q_best = q; Error = minusError;
        fprintf('%5d %5d     %10.8f\n',p_best,q_best,Error)
     end
     p_plus = ceil(q*pi); plusError = abs(p_plus/q - pi);
     if plusError < Error
%       An improved quotient has been discovered...
        p_best = p_plus; q_best = q; Error = plusError;
        fprintf('%5d %5d     %10.8f\n',p_best,q_best,Error)
     end
  end
  
