% Rational approximation of pi

M = input('Enter M: ');
% Best q, p, and error so far
qBest=1; pBest=1;
err_pq = abs(pBest/qBest - pi);

% Check all possible denominators
for q = 1:M
% At this q, check all possible numerators
for p = 1:M
if abs(p/q - pi) < err_pq % best p/q found
fprintf(' found better fraction %d/%d\n', p, q)
err_pq = abs(p/q - pi);
pBest= p;
qBest= q;
end
end
end

myPi = pBest/qBest;
fprintf('pi ~ %d/%d = %f\n', pBest, qBest, myPi)