
%
% Rational Approximation of pi
%
% Input a positive integer M and then prints the best approximation to pi
% of the form p/q, where p and q are integers that satisfy 1 <= p <= M and
% 1 <= q <= M.

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

% 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
    % Initializations for the p-search...
    p0 = 1;
    e0 = abs(pi - p0/q);
    % For this q, find the best numerator p0...
    for p = 1:M
        if (abs(pi - p/q) < e0) then
            % A new best numerator has been found for this q...
            p0 = p;
            e0 = abs(pi - p/q);
        endif
    endfor
    % Check to see if we have a new best quotient for this q...
    if  (e0 < err_pq) then
        pBest  = p0;
        qBest  = q;
        err_pq = e0;
    endif
endfor

MyPi = pBest/qBest;
% Display Results 
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)

