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
⇒ 0.00000026676

Programming Note: 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.

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 9.

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.

© 1996–2020 John W. Eaton
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions.
https://octave.org/doc/v6.3.0/Rational-Approximations.html