% Script SimplerEg3_1
% Rational Approximation of pi
% This version is simpler than Eg3_1--unnecessary variables (e0 and p0) and
% the related statements have been removed.

% Acquire the numerator/denominator limit...
M = input('Enter M:');

% Initializations...
pBest = 1;                      % Best numerator ``found so far''
qBest = 1;                      % Best denominator ``found so far''...
err_pq = abs(pBest/qBest - pi); % Error in current best fraction...

% Check out all possible denominators...
for q = 1:M
    % For this q, find the best numerator p0...
    for p = 1:M
        if abs(pi - p/q) < err_pq
            % A new set of best numerator and denominator has been found 
            err_pq= abs(pi - p/q);
            pBest= p;
            qBest= q;
        end
    end
end
MyPi = pBest/qBest;
% Display Results
clc
fprintf('M     = %1d\npBest = %1d\nqBest = %1d\n',...
        M,pBest,qBest)
fprintf('MyPi  = %17.15f\npi    = %17.15f\nerror = %17.15f\n\n',...
        MyPi,pi,err_pq)

