Reference

Everything in the library

Every item below is a named export of @ratmath/core; the default export is an object holding the same values. Inputs written q accept a safe integer number, a bigint, a string such as "3/4", "0.#3" or "1..1/2", or a Core value. That applies to constructors and helper functions; the arithmetic methods (add, multiply, …) take Core values, so write half.add(new Rational(1)) or R`1/2 + 1`, not half.add(1). Operations never return NaN or infinity: division by zero, 0^0, an interval divisor containing 0 and malformed text throw an Error. The shipped index.d.ts has the exact TypeScript signatures.

Values

classconstructnotes
Integernew Integer(n), Integer.from(n), Integer.fromRational(q)n: safe integer, bigint, decimal string or Integer; .value is the bigint
Rationalnew Rational(p, q = 1), Rational.from(q)always lowest terms, positive denominator; .numerator, .denominator are bigints; a string argument may be any literal (a second argument divides it)
RationalIntervalnew RationalInterval(a, b), RationalInterval.point(q), .fromString("a:b")closed; start/end keep the written order, low/high are sorted
RationalIntervalSetnew RationalIntervalSet(components), .point(q), .fromInterval(I)finite unions with open, closed or unbounded ends
CertifiedApproximationnew CertifiedApproximation(candidate, enclosure, options?)usually made by parsing "1.5?"; the enclosure is the guarantee
Fractionnew Fraction(p, q = 1, { allowInfinite })not reduced; a/0 allowed as ±infinity with the option
FractionIntervalnew FractionInterval(lowFraction, highFraction)mediant splitting that keeps unreduced ends
RegionRegion.parse(text, { params, variable }), R.region`…`sets of rationals from chains; see Chains
MultiRegionRegion.parse(text, { variables, params }), MultiRegion.parse, R.region`0:x:1 && 0:y:x`regions on several variables: contains, match, cells, section, breakpoints; see Chains
BaseSystemnew BaseSystem(digits, name?, { radix, digitOffset, allowReserved })presets BINARY … BASE64, fromBase(n), prefix registry
NumeralSystemnew NumeralSystem({ kind, radix, tokens })kinds ordinary, multiToken, balanced, negative
TypePromotionstatic methods onlyInteger → Rational → RationalInterval dispatch

Integer

methodresult
add, subtract, multiplyInteger, or a promoted type for a Rational or interval operand
divide(b)Integer when exact, else Rational
floorDivide, floorModulo, divmodfloor quotient, remainder with the sign of the divisor, [q, r]
modulo(b)remainder with the sign of a (BigInt %)
pow(n), E(k)power (negative n gives a Rational), times 10k10^k
gcd, lcm, factorial, doubleFactorial, bitLengthnumber theory
abs, negate, sign, isZero, isEven, isOdd, isPositive, isNegativesign and parity
equals, compareTo, lessThan, lessThanOrEqual, greaterThan, greaterThanOrEqualcomparisons (accept Rationals too)
digits(base?), digitAt(k, base?), placeValue(k, base?)digits, most significant first; the digit in place k and its value
toString(radix?), toBase(system), toNumber(), toRational()conversions

Rational

methodresult
add, subtract, multiply, divideexact; an interval operand gives a RationalInterval
negate, reciprocal, abs, pow(n), E(k)exact
floor(), ceil(), trunc(), round(mode?), roundTo(places, mode?)Integers (bigint via .value; roundTo gives a Rational); modes from ROUNDING_MODES or a function (see rounding): half-up (default, school rounding), half-even (banker's rounding), toward-zero, floor, ceil
digitAt(k, base?), placeValue(k, base?)the digit in place k (0 ones, 1 tens, −1 tenths) and its value
toString(), toMixedString(), toDecimal(digits?), toNumber()"-9/4", "-2..1/4", display decimal, a float
toRepeatingDecimal(limit?, onLimit?), toRepeatingDecimalWithPeriod(opts?)"0.1#6"; period limit 30 by default
computeDecimalMetadata(maxPeriod?)whole part, pre-period, period digits and length
toScientificNotation(useRepeat?, precision?)"1.2345E4"
toBase(system), toRepeatingBase(system, opts?), toRepeatingBaseWithPeriod, periodModulo(system)other bases
toContinuedFraction(opts?), toContinuedFractionString(opts?)[3n, 7n, 16n], "3.~7~16"
convergents(opts?), getConvergent(k)convergents, with long and intermediates options
bestApproximation(maxDen), bestConvergent(maxDen), approximationError(x)closest fractions with bounded denominators
Rational.fromContinuedFraction, fromContinuedFractionString, convergentsFromCFstatic builders
comparisons, equals, bitLengthas for Integer

RationalInterval

methodresult
add, subtract, multiply, divide, negate, reciprocateintervals containing every possible result; dividing by an interval that contains 0 throws
pow(n) / mpow(n)image {xn}\{x^n\} / product of n independent factors
overlaps, contains, containsValue, containsZero, equalsbooleans
intersection, unionan interval or null
midpoint, mediant, shortestDecimal(base?), denominatorInterval(d?), randomRational(d?)points inside
toString, toMixedString, toRepeatingDecimal, compactedDecimalInterval, relativeDecimalInterval, relativeMidDecimalInterval"1/3:2/3", "1.2[24:35]", "1.2295[+-55]", …
E(k), bitLength()scaling, size

RationalIntervalSet and range arithmetic

memberresult
containsValue, contains, equals, union, intersection, hull, toRationalIntervalset operations; toString() gives "(2,8] U [10,12]"
asRationalIntervalSet(v)any Core number as a set
rangeAdd, rangeSubtract, rangeMultiply, rangeDivide, rangeReciprocal, rangeNegate, rangeAbsoluteValue, rangeIntegerPower{ range, domain, … }: exact images of sets; dividing by a set that contains 0 gives the image of the rest, and domain records what was left out
checkRangeOperationResult, RANGE_OPERATION_RESULT_SCHEMA, RANGE_ARITHMETIC_CHECKER_IDvalidation of stored results

Certified approximations

memberresult
candidate, enclosure, low, high, representation, sourceId, dependenciesthe guess, the guarantee, and where it came from
add, subtract, multiply, divide, negate, reciprocal, pow, Enew approximations whose enclosure contains every possible result
possibleRelations(a, b), a.possibleRelationsTo(b), Relationbit mask of Relation.LESS | EQUAL | GREATER
certifiedRadixPrefix, certifiedContinuedFractionPrefixbuild from digits or coefficients
boundedDecimalApproximation(q, { fractionalDigits }), boundedContinuedFractionApproximation(q, { maxTerms })an exact value cut to a budget, with its enclosure
normalizeCertifiedApproximation(candidate, enclosure)a plain value when the enclosure is a point
toRationalInterval, toRational, copy, toString, toJSONconversions

Text in, values out

exportresult
R`…`exact arithmetic on literals: Integer, Rational, RationalInterval, CertifiedApproximation, or a boolean for a chain; see R
rounding(mode?), ROUNDING_MODES, isRoundingMode(m)a rounder for one convention (named, or a function returning floor or ceil): r(x) an Integer, r(x, places) a Rational; it changes nothing globally
R.base(radix)`…`, R.between`…`, R.region`…`another base; a chain typed boolean; a Region
parseNumber(text)any literal: Integer, Rational, RationalInterval or CertifiedApproximation
parseRational, parseDecimal, parseRepeatingDecimal, parseMixedNumber, parseContinuedFraction, parseInterval, parseCertifiedApproximationone literal kind each; see Number literals

Fast first, exact last

A separate entry point, @ratmath/core/refine, holds the two-step answer shared by linalg, analytic and graphics: a float preview at once, the exact answer after.

exportresult
new Refinement(quick, exact)quick: () => {value, trust}; exact: a generator that yields progress and returns {value, via}
.quick{stage: "float", value, trust}, computed on first read
.exact(), .exactStage()the exact value, or its record {stage: "exact", value, via}; cached
.stages()generator: the preview, progress ticks, the exact record
.settle({signal, sliceMs, onStage, onProgress})promise of the exact value, computed in slices; rejects with an AbortError
live(compute, onStage, {idleMs, sliceMs, onProgress, onError})update(…args) for a slider: previews every call, finishes only the latest; update.cancel()

Units and quantities

A separate entry point, @ratmath/core/units; see Units and quantities.

exportresult
Q(value, unit), Q("value unit")a Quantity in the standard catalogue; value is an exact Core number, bigint, safe integer or literal string
.to(unit), .valueIn(unit), .toBase(), .simplify()exact conversions; base SI units; a named coherent unit (N, J, W…)
.add, .subtract, .negate, .multiply, .divide, .inverse, .pow(n)a Quantity, or a plain number when the dimensions cancel; temperature points follow affine rules
.relation(q), .compare(q), .equals(q)Relation mask; −1/0/1 (throws if undecided); certainly equal
.value, .unit, .point, .dimensions, .toString({style, format})the magnitude in its own unit, the Unit, whether it is a temperature point
units.get(name), units.parse(expr), units.has(name)a Unit; prefixes (km, MiB) and expressions ("kg*m^2/s^2", "N m", "m·s⁻²")
units.extend({scalars}), .define(name, definition, options), .register(key, unit), .groups(), .names()a copy to add units to; definitions from "201.168 m", a Quantity, a Unit or {dimensions, scale, piPower}
Unit: .name, .dimensions, .scale, .piPower, .kind, .offset, .prefixes; .multiply, .divide, .inverse, .pow, .equals, .isCompatiblesize is scale·π^piPower base units; kind is linear, affine or difference
constantsc, h, e, kB, NA, R, g0 (exact) and G (an interval)
coreScalars, UnitSystem, Unit, Quantity, BASE_DIMENSIONS, dimensionsEqual, formatDimensions, isUnit, isQuantitythe pieces, for building your own system

Lists

exportresult
range(start, end, step = 1)inclusive ExactList
seq(list | start, end[, step], fn?)ExactList of terms
sum(…), product(…)exact total (0 and 1 when empty)
exact(iterable), ExactListArray subclass with sum, product, add, subtract, multiply, divide, pow, min, max

Fractions and the Stern–Brocot tree

memberresult
add, subtract (equal denominators), multiply, divide, pow, scale, reduce, Earithmetic that keeps the written components
mediant, Fraction.mediant, fareyParents, Fraction.mediantPartner, isMediantTriple, isFareyTriplemediants and Farey neighbours
sternBrocotPath, Fraction.fromSternBrocotPath, sternBrocotParent, sternBrocotChildren, sternBrocotDepth, sternBrocotAncestors, isSternBrocotValidthe tree
FractionInterval: mediantSplit, partitionWithMediants(depth), partitionWith(fn), toRationalIntervalsubdivision

Bases

memberresult
BaseSystem: toDecimal(text), fromDecimal(bigint), getChar(k), isValidString, equals, withCaseSensitivityinteger conversion in any alphabet
BaseSystem.fromBase(n), createPattern(kind, size), registerPrefix, getSystemForPrefix, getPrefixForSystemfactories and the 0x-style prefixes
NumeralSystem: parse, format(q, { maxDigits, mode }), normalize, places, locale, tokenizeexact parsing and bounded expansion with evidence
NUMERAL_SYSTEM_SCHEMA, NUMERAL_LIMITSdescriptor schema and limits

Types and JSON

exportresult
isInteger, isRational, isRationalInterval, isRationalIntervalSet, isCertifiedApproximation, isFraction, isFractionInterval, isBaseSystem, isCoreNumbertype guards
reviveCoreValuea JSON.parse reviver for the tagged toJSON() output
TypePromotion.getTypeLevel, promoteToLevel, promoteToCommonType, add, subtract, multiply, divide, power, multiplyPower, negatedispatch for evaluators
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