Continued fractions
Every real number is a₀ + 1/(a₁ + 1/(a₂ + …)) with whole numbers aₖ, written [a₀; a₁, a₂, …]. Rationals stop, quadratic irrationals repeat forever, and the cut-off fractions are the best rational approximations there are.
These functions moved here from @ratmath/algebraic, which still provides the algebraic numbers they work on.
Exact terms for any algebraic number
For an algebraic , the root of in an interval, the next term is : shrink the interval until it lies between two integers. Then , and is a root of
shifted by with its coefficients reversed, in the interval mapped by . No digit of is approximated, so every term is right. shows no pattern, and nobody knows whether its terms are bounded.
import { continuedFraction, convergents, periodicContinuedFraction, fromContinuedFraction, pell, fundamentalUnit } from "@ratmath/numtheory";
import { nthRoot, sqrt, fromRational } from "@ratmath/algebraic";
continuedFraction(nthRoot(fromRational(2), 3), 8); // [1n, 3n, 1n, 5n, 1n, 1n, 4n, 1n]
continuedFraction("103993/33102"); // [3n, 7n, 15n, 1n, 292n]: a convergent of π
convergents([1, 2, 2, 2]).map(String); // ["1", "3/2", "7/5", "17/12"]
The convergents satisfy , , and . Each is closer to than any fraction with a smaller denominator. A large next term means an unusually good convergent: 's 355/113 comes right before the term 292.
Quadratic irrationals repeat
Lagrange: the expansion is eventually periodic exactly when is a quadratic irrational. Written as with , each step is
all in integers. Only finitely many pairs occur, so one repeats, and the period is read off exactly.
periodicContinuedFraction(sqrt(fromRational(7))); // { preperiod: [2n], period: [1n, 1n, 1n, 4n] }
fromContinuedFraction([1], [2]); // √2 exactly: [1; 2, 2, 2, …]
Pell's equation and units
( not a square) always has solutions, and the smallest comes from the period of : if the period has length , the convergent just before the end of the first period gives . For odd that solves the equation, and a second period solves the equation. is Fermat's challenge to the English mathematicians. The same computation gives the fundamental unit of the integers of : every unit is (Dirichlet). The Pell page solves for any .
pell(61); // { x: 1766319049n, y: 226153980n, negative: { x: 29718n, y: 3805n } }
fundamentalUnit(94); // { unit: 2143295 + 221064√94, norm: 1 }
@ratmath/numtheory and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.