function  [num,den] = printrat(x,max)
% usage: [p,q] = printrat(x,depth)
% description: this routine displays each entry of the matrix x in
% an approximate rational form, where the approximation is obtained
% via continued fractions.  If return arguments are specified, the
% numerators are stored in the matrix p and denominators in q. If
% optional second argument is specified, continued fractions are
% calculated to that depth (default: depth = 40).

% local variables:
% j,k,m: index variables

tol = 1e-12;
if (nargin < 2)
  max = 40;
end;
[nr,nc]=size(x);
num = zeros(size(x));
den  = zeros(size(x));
p = zeros(1,3);
q = zeros(1,3);
disp('');
for j = 1:nr
  for k = 1:nc
    alpha = x(j,k);
    a = floor(alpha);
    p(1) = 0;
    q(1) = 1;
    p(2) = 1;
    q(2) = 0;
    for m = 1:max
      p(3) = a*p(2) + p(1);
      q(3) = a*q(2) + q(1);
      if (abs(x(j,k)-p(3)/q(3))<tol | (alpha - a) < tol)
        break;
      else
        p(1:2) = p(2:3);
        q(1:2) = q(2:3);
        alpha = 1/(alpha - a);
        a = floor(alpha);
      end;
    end;
    num(j,k) = p(3);
    den(j,k) = q(3);
    fprintf(1, '%d/%d  ',num(j,k),den(j,k));
  end;
  disp(' ');
end;
disp(' ');

