ContinuedFraction.js is published as continuedfraction.js. It generates simple and generalized continued fractions and evaluates a bounded number of terms to an exact Fraction.js convergent.
Use it to inspect continued-fraction terms or construct rational approximations of square roots, real values, rational values, φ, e, π, and 4/π. Use Fraction.js directly when the input is already rational and no term sequence is needed. It is not an arbitrary-precision transcendental-function package: each result is a rational convergent chosen by the requested term count.
Features
Generate the simple continued‑fraction expansion of √N
Convert any real number or rational to its continued‑fraction
Infinite generators for classic constants: φ (golden ratio), e, π, 4/π
Evaluate (simple or generalized) continued fractions to a Fraction
Enumerate exact convergents or collect a bounded number of terms
Strict TypeScript types for terms, sources, and coefficients
The package supports Node.js 20 or newer. Its CommonJS build uses the declared Fraction.js dependency; the ESM and standalone browser builds are self-contained. CommonJS also exposes .default and .ContinuedFraction aliases for compatibility.
Recipes
Approximate an irrational square root
sqrt() generates the periodic simple continued fraction; eval() consumes at most the requested number of terms.
sqrt(N) expects a non-negative safe integer and throws RangeError otherwise. Perfect squares terminate after one term; non-squares produce an infinite generator.
Inspect and reconstruct a rational value
Rational expansions terminate. Fraction.js represents their terms as BigInt, so convert them before JSON serialization when the values are known to fit safely in Number.
Do not convert large BigInt terms to Number unless they are within the safe-integer range.
Build convergents for e and a perfect square
Generator functions can be passed directly to eval(). This creates a new generator for each evaluation.
import ContinuedFraction from 'continuedfraction.js';const e = ContinuedFraction.eval(ContinuedFraction.E, 10);const squareTerms = [...ContinuedFraction.sqrt(49)];console.log(e.toFraction()); // "1457/536"console.log(squareTerms.map(Number)); // [7]
Always bound iteration over E(), PHI(), PI(), FOUR_OVER_PI(), or a non-square sqrt() generator. Spreading an infinite generator never completes.
Inspect every convergent
convergents() yields exact Fraction.js values lazily. fromTerms() turns an existing sequence into a generator, while toArray() safely collects a bounded prefix.
// 2) Continued‑fraction of a decimallet cnt = 0;for (let piCf of ContinuedFraction.fromNumber(Math.PI)) { console.log(piCf); if (cnt++ >= 10) break;}
// 3) Golden ratio φ termsconst phiGen = ContinuedFraction.PHI();console.log(phiGen.next().value); // 1, and forever 1…
// 4) Evaluate the first 10 terms of e’s CF to a Fractionconst approxE = ContinuedFraction.eval(ContinuedFraction.E, 10);console.log(approxE.toFraction()); // "1457/536"