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
| class | construct | notes |
|---|---|---|
| Integer | new Integer(n), Integer.from(n), Integer.fromRational(q) | n: safe integer, bigint, decimal string or Integer; .value is the bigint |
| Rational | new 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) |
| RationalInterval | new RationalInterval(a, b), RationalInterval.point(q), .fromString("a:b") | closed; start/end keep the written order, low/high are sorted |
| RationalIntervalSet | new RationalIntervalSet(components), .point(q), .fromInterval(I) | finite unions with open, closed or unbounded ends |
| CertifiedApproximation | new CertifiedApproximation(candidate, enclosure, options?) | usually made by parsing "1.5?"; the enclosure is the guarantee |
| Fraction | new Fraction(p, q = 1, { allowInfinite }) | not reduced; a/0 allowed as ±infinity with the option |
| FractionInterval | new FractionInterval(lowFraction, highFraction) | mediant splitting that keeps unreduced ends |
| Region | Region.parse(text, { params, variable }), R.region`…` | sets of rationals from chains; see Chains |
| MultiRegion | Region.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 |
| BaseSystem | new BaseSystem(digits, name?, { radix, digitOffset, allowReserved }) | presets BINARY … BASE64, fromBase(n), prefix registry |
| NumeralSystem | new NumeralSystem({ kind, radix, tokens }) | kinds ordinary, multiToken, balanced, negative |
| TypePromotion | static methods only | Integer → Rational → RationalInterval dispatch |
Integer
| method | result |
|---|---|
| add, subtract, multiply | Integer, or a promoted type for a Rational or interval operand |
| divide(b) | Integer when exact, else Rational |
| floorDivide, floorModulo, divmod | floor 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 |
| gcd, lcm, factorial, doubleFactorial, bitLength | number theory |
| abs, negate, sign, isZero, isEven, isOdd, isPositive, isNegative | sign and parity |
| equals, compareTo, lessThan, lessThanOrEqual, greaterThan, greaterThanOrEqual | comparisons (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
| method | result |
|---|---|
| add, subtract, multiply, divide | exact; 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, convergentsFromCF | static builders |
| comparisons, equals, bitLength | as for Integer |
RationalInterval
| method | result |
|---|---|
| add, subtract, multiply, divide, negate, reciprocate | intervals containing every possible result; dividing by an interval that contains 0 throws |
| pow(n) / mpow(n) | image / product of n independent factors |
| overlaps, contains, containsValue, containsZero, equals | booleans |
| intersection, union | an 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
| member | result |
|---|---|
| containsValue, contains, equals, union, intersection, hull, toRationalInterval | set 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_ID | validation of stored results |
Certified approximations
| member | result |
|---|---|
| candidate, enclosure, low, high, representation, sourceId, dependencies | the guess, the guarantee, and where it came from |
| add, subtract, multiply, divide, negate, reciprocal, pow, E | new approximations whose enclosure contains every possible result |
| possibleRelations(a, b), a.possibleRelationsTo(b), Relation | bit mask of Relation.LESS | EQUAL | GREATER |
| certifiedRadixPrefix, certifiedContinuedFractionPrefix | build 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, toJSON | conversions |
Text in, values out
| export | result |
|---|---|
| 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, parseCertifiedApproximation | one 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.
| export | result |
|---|---|
| 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.
| export | result |
|---|---|
| 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, .isCompatible | size is scale·π^piPower base units; kind is linear, affine or difference |
| constants | c, h, e, kB, NA, R, g0 (exact) and G (an interval) |
| coreScalars, UnitSystem, Unit, Quantity, BASE_DIMENSIONS, dimensionsEqual, formatDimensions, isUnit, isQuantity | the pieces, for building your own system |
Lists
| export | result |
|---|---|
| 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), ExactList | Array subclass with sum, product, add, subtract, multiply, divide, pow, min, max |
Fractions and the Stern–Brocot tree
| member | result |
|---|---|
| add, subtract (equal denominators), multiply, divide, pow, scale, reduce, E | arithmetic that keeps the written components |
| mediant, Fraction.mediant, fareyParents, Fraction.mediantPartner, isMediantTriple, isFareyTriple | mediants and Farey neighbours |
| sternBrocotPath, Fraction.fromSternBrocotPath, sternBrocotParent, sternBrocotChildren, sternBrocotDepth, sternBrocotAncestors, isSternBrocotValid | the tree |
| FractionInterval: mediantSplit, partitionWithMediants(depth), partitionWith(fn), toRationalInterval | subdivision |
Bases
| member | result |
|---|---|
| BaseSystem: toDecimal(text), fromDecimal(bigint), getChar(k), isValidString, equals, withCaseSensitivity | integer conversion in any alphabet |
| BaseSystem.fromBase(n), createPattern(kind, size), registerPrefix, getSystemForPrefix, getPrefixForSystem | factories and the 0x-style prefixes |
| NumeralSystem: parse, format(q, { maxDigits, mode }), normalize, places, locale, tokenize | exact parsing and bounded expansion with evidence |
| NUMERAL_SYSTEM_SCHEMA, NUMERAL_LIMITS | descriptor schema and limits |
Types and JSON
| export | result |
|---|---|
| isInteger, isRational, isRationalInterval, isRationalIntervalSet, isCertifiedApproximation, isFraction, isFractionInterval, isBaseSystem, isCoreNumber | type guards |
| reviveCoreValue | a JSON.parse reviver for the tagged toJSON() output |
| TypePromotion.getTypeLevel, promoteToLevel, promoteToCommonType, add, subtract, multiply, divide, power, multiplyPower, negate | dispatch for evaluators |
@ratmath/core in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.