### 17.7 Rational Approximations ¶

`s =` rat `(x)` ¶
`s =` rat `(x, tol)` ¶
`[n, d] =` rat `(…)` ¶

  Find a rational approximation of x to within the tolerance defined by tol.

  If unspecified, the default tolerance is `1e-6 * norm (x(:), 1)`.

  When called with one output argument, return a string containing a continued fraction expansion (multiple terms).

  When called with two output arguments, return numeric matrices for the numerator and denominator of a fractional representation of x such that `x = n ./ d`.

  For example:

      s = rat (pi)
      ⇒  s = 3 + 1/(7 + 1/16)

      [n, d] = rat (pi)
      ⇒  n =  355
      ⇒  d =  113

      n / d - pi
      ⇒  2.6676e-07

  Complex inputs are similar:

      s = rat (0.5 + i * pi)
      ⇒  s = complex (1 + 1/(-2), 3 + 1/(7 + 1/16))

      [n, d] = rat (0.5 + i * pi)
      ⇒  n =  113 + 710i
      ⇒  d =  226

      n / d - (0.5 + i * pi)
      ⇒  0 + 2.6676e-07i

  Programming Notes:

  1. With one output `rat` produces a string which is a continued fraction expansion. To produce a string which is a simple fraction (one numerator, one denominator) use `rats`.

  2. The string output produced by `rat` can be passed to `eval` to get back the original input up to the tolerance used.

  See also: rats, format.

`s =` rats `(x)` ¶
`s =` rats `(x, len)` ¶

  Convert x into a rational approximation represented as a string.

  A rational approximation to a floating point number is a simple fraction with numerator N and denominator D such that `x = N/D`.

  The optional second argument defines the maximum length of the string representing the elements of x. By default, len is 13.

  If the length of the smallest possible rational approximation exceeds len, an asterisk (*) padded with spaces will be returned instead.

  Example conversion from matrix to string, and back again.

      r = rats (hilb (4));
      x = str2num (r)

  See also: rat, format.