rat

Rational approximation of a number by continued fractions.

Category: Mathematics > Elementary Math

Syntax

S = rat(X)

Returns a character vector with the continued fraction expansion of X.

[N, D] = rat(X)

Returns numerators N and denominators D so that N./D approximates X.

[N, D] = rat(X, tol)

Uses the tolerance tol on the relative error.

Description

The algorithm repeatedly takes the nearest integer and inverts the remainder, which yields the convergents of the continued fraction. It stops once the approximation is within the tolerance. Thus pi becomes 355/113, a famously good approximation.

The text form uses rounding to the nearest integer, not truncation, so rat(0.75) is written 1 + 1/(-4), which is equal to 0.75. Use rats for a display of fractions.

Input arguments

X
Real array.
tol
Tolerance for the approximation. The default is 1e-6*norm(X(:), 1).

Output arguments

S
Text such as 3 + 1/(7 + 1/(16)): each term is a rounded value, so some of them are negative.
N, D
Integer-valued arrays of the same size as X; the denominator is positive.

Example

Fractions from decimals

[n, d] = rat(0.75)
[n, d] = rat(pi)
rat(pi)
Output
n = 3
d = 4
n = 355
d = 113
ans = '3 + 1/(7 + 1/(16))'

See also

rats gcd format round