Topic

Continued fractions

Every rational has a finite continued fraction, and its prefixes, the convergents, are the best fractions with small denominators. Core computes them exactly, and writes them as 3.~7~16.

Euclid's algorithm, written down

Take the integer part, flip what is left over, and repeat:

355113=3+17+116=[3;7,16]. \frac{355}{113} = 3 + \cfrac{1}{7 + \cfrac{1}{16}} = [3; 7, 16].

RatMath writes [3;7,16][3; 7, 16] as 3.~7~16: the integer part, a dot, then the remaining terms each after a ~.

The coefficients are the quotients of Euclid's algorithm on 355355 and 113113, so the expansion of p/qp/q ends after about log⁡q\log q steps. The last coefficient of the canonical form is greater than 1, because […,a,1]=[…,a+1][\ldots, a, 1] = [\ldots, a + 1]; the option { long: true } gives the other form.

import { Rational, parseContinuedFraction } from "@ratmath/core";

const v = new Rational(333, 106);
v.toContinuedFraction();                        // [3n, 7n, 15n]
v.toContinuedFractionString();                  // "3.~7~15"
new Rational(4, 3).toContinuedFraction({ long: true });   // [1n, 2n, 1n]
Rational.fromContinuedFraction([3n, 7n, 15n, 1n]).toString();   // "355/113"
parseContinuedFraction("~-3.~1~3").toString();  // "-9/4" (a negative first term)

Negative values: - or ~-

A minus sign in front means negation, as everywhere else: -3.~1~3 is −(3. ⁣∼ ⁣1 ⁣∼ ⁣3)-(3.\!\sim\!1\!\sim\!3), the negative of 3+11+13=1543 + \cfrac{1}{1 + \cfrac13} = \tfrac{15}{4}, so −154-\tfrac{15}{4}. To make the first term itself negative, put a ~ before the sign: ~-3.~1~3 is

−3+11+13=−94=[−3;1,3]. -3 + \cfrac{1}{1 + \cfrac{1}{3}} = -\frac94 = [-3; 1, 3].

Only the first term can be negative; the later terms are positive. Every parser (R, parseNumber, parseContinuedFraction, Rational.fromContinuedFractionString, NumeralSystem.parse) reads both forms this way, as RiX does. The canonical expansion of a negative rational has a negative first term, so toContinuedFractionString() writes it with the ~, and the output reads back as the same value.

parseContinuedFraction("-3.~1~3").toString();   // "-15/4": -(3.~1~3)
parseContinuedFraction("~-3.~1~3").toString();  // "-9/4":  first term -3
new Rational(-9, 4).toContinuedFraction();       // [-3n, 1n, 3n]
new Rational(-9, 4).toContinuedFractionString(); // "~-3.~1~3"
new Rational(-15, 4).toContinuedFractionString(); // "~-4.~4": -15/4 = -4 + 1/4

Convergents

Cutting the expansion after aka_k gives the convergent pk/qkp_k/q_k. They obey the recurrence

pk=ak pk−1+pk−2,qk=ak qk−1+qk−2, p_k = a_k\,p_{k-1} + p_{k-2}, \qquad q_k = a_k\,q_{k-1} + q_{k-2},

starting from p−1/q−1=1/0p_{-1}/q_{-1} = 1/0 and p−2/q−2=0/1p_{-2}/q_{-2} = 0/1. Neighbouring convergents satisfy pkqk−1−pk−1qk=(−1)k−1p_k q_{k-1} - p_{k-1} q_k = (-1)^{k-1}, so they alternate around the value and close in on it:

∣x−pkqk∣≤1qk qk+1≤1qk2(k before the last term). \left| x - \frac{p_k}{q_k} \right| \le \frac{1}{q_k\, q_{k+1}} \le \frac{1}{q_k^2} \qquad (k \text{ before the last term}).

For an irrational xx the first inequality is strict; for a rational it can be an equality, as with ∣355113−227∣=17⋅113\left|\tfrac{355}{113} - \tfrac{22}{7}\right| = \tfrac{1}{7 \cdot 113}.

A decimal like 3.14159265358979 is itself an exact rational, so its expansion is finite too; its first terms agree with those of π\pi ([3;7,15,1,292,…][3; 7, 15, 1, 292, \ldots]) for as long as the digits do.

Best approximations

Two different questions have nearly the same answer:

  • bestApproximation(N): the fraction with denominator at most NN that is closest to xx. It may be a semiconvergent pk−1+j pkqk−1+j qk\frac{p_{k-1} + j\,p_k}{q_{k-1} + j\,q_k}, an intermediate fraction between two convergents.
  • bestConvergent(N): the last convergent with denominator at most NN. Convergents are exactly the best approximations "of the second kind", the ones minimizing ∣qx−p∣|q x - p|.
const pi = new Rational(355, 113);
pi.bestApproximation(100).toString();     // "311/99"
pi.bestConvergent(100).toString();        // "22/7"
pi.convergents().map(String);             // ["3", "22/7", "355/113"]
new Rational(4, 3).convergents({ intermediates: true }).map(String);   // ["1", "2", "3/2", "4/3"]

With intermediates: true, convergents() also lists the semiconvergents between principal convergents. These are the fractions met on the way down the Stern–Brocot tree: a coefficient aka_k is a run of aka_k steps in one direction.

Prefixes and limits

Options maxTerms (and maxCount for convergents) cap the work, default Rational.DEFAULT_CF_LIMIT. A capped string ends in ~... so it cannot be mistaken for the exact value; the exact parser rejects it. To mark a prefix as a certified approximation instead, write 3.~7~15?: the value lies between the two fractions the prefix allows (see Certified approximations).

Try itEdit the code and run it with @ratmath/core in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.
Ctrl/⌘ + Enter runs