Numbers

Recognising numbers

You have 1.6180339887 from a calculation and suspect it is (1 + √5)/2. Lattice reduction finds the small integer polynomial that a decimal nearly satisfies; the library then checks the guess exactly against the digits.

Small polynomials are short vectors

Suppose x is known to D digits and we look for integers a₀ … a_d, not all zero and not large, with a₀ + a₁x + … + a_d·x^d = 0. Take C ≈ 10^D and the d + 1 vectors

bᵢ = ( eᵢ , round(C·xⁱ) ), i = 0 … d

(eᵢ is the i-th unit vector). The combination Σ aᵢbᵢ is (a₀, …, a_d, C·Σaᵢxⁱ + rounding). When the polynomial nearly vanishes at x, the last entry is tiny, so the whole vector is short. Other combinations have a last entry around C·(something not small). Finding the shortest vector of a lattice is hard, but the LLL algorithm (Lenstra, Lenstra and Lovász, 1982) finds one within a factor 2^(d/2) of it in polynomial time, and that is plenty here.

LLL repeats two moves on the basis: size reduction (subtract rounded multiples of earlier vectors, so each Gram–Schmidt coefficient is at most 1/2) and a swap of neighbours whenever the Lovász condition |b*ₖ|² ≥ (3/4 − μ²)|b*ₖ₋₁|² fails. Here it runs in exact rational arithmetic.

A guess, checked

The first reduced vector gives a candidate polynomial. It is factored, and the library looks for an irreducible factor with a root inside the interval the digits allow (one unit in the last digit either way). There is always some polynomial that fits a decimal, so a fit only counts as recognition when it is much smaller than the digits: a polynomial of degree d with coefficients up to H takes about (d + 1)·log₁₀H digits to pin down, and the library asks for 3 digits more than that. Without that margin, π = 3.14159265358979 would be "recognised" as a fraction with 8-digit numerator and denominator.

A recognised number is a guess that agrees with every digit given, not a proof that the original quantity is that number; more digits could refute it. What it does give you is an exact candidate to verify by other means, for instance by substituting it back with the exact arithmetic of this library.

In code

import { recognize, format, lll } from "@ratmath/algebraic";
const r = recognize("0.9238795325112867");
format(r.value);    // "√(2 + √2)/2"   (that is cos(π/8))
r.poly;             // [1n, 0n, -8n, 0n, 8n]
r.digitsUsed;       // 16
r.digitsNeeded;     // 6
recognize("3.14159265358979");   // null: nothing small enough fits
lll([[1n, 0n, 0n, 10000n], [0n, 1n, 0n, 14142n], [0n, 0n, 1n, 20000n]]);  // reduced basis

Options: { maxDegree = 4, margin = 3 }. The input can be a decimal string (a trailing "…" is allowed) or an interval [lo, hi].

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