Topic

Bases and numeral systems

The same exact value can be written in any base. BaseSystem converts integers and fractions to and from any digit alphabet; NumeralSystem adds balanced and negative bases, multi-character digits, and bounded conversions that report how far they got.

Repeating in another base

Whether a fraction ends depends on the base. 110\tfrac1{10} ends in base 10 but repeats in base 2 (0.00011‾0.0\overline{0011}), while 13\tfrac13 repeats in base 10 and ends in base 3 (0.10.1). The rule is the one from Rationals with 10 replaced by the base bb: in lowest terms p/qp/q ends exactly when every prime factor of qq divides bb, and otherwise the period is the order of bb modulo the part of qq that shares no factor with bb.

import { Rational, BaseSystem } from "@ratmath/core";

const third = new Rational(1, 3);
third.toRepeatingBase(BaseSystem.BINARY);           // "0.#01"
third.toRepeatingBase(BaseSystem.TERNARY);          // "0.1#0" (#0: it terminates)
new Rational(1, 10).toRepeatingBaseWithPeriod(BaseSystem.BINARY);
// { baseStr: "0.0#0011", period: 4, limitHit: false }
third.toBase(BaseSystem.BINARY);                    // "1/11": numerator and denominator in base 2

Digit alphabets

A BaseSystem is an ordered list of single-character digits; the first is worth 0. Presets cover the common bases (BINARY, OCTAL, DECIMAL, DUODECIMAL, HEXADECIMAL, VIGESIMAL, BASE36, BASE60, BASE62, BASE64), and BaseSystem.fromBase(n) uses 0-9a-zA-Z for any base up to 62. Characters RatMath uses as notation (+ - * / ^ ! ( ) [ ] : . # ~) cannot be digits.

const abc = new BaseSystem("abc", "ABC digits");
abc.fromDecimal(5n);                            // "bc", since 5 = 1·3 + 2
BaseSystem.HEXADECIMAL.toDecimal("ff");         // 255n
BaseSystem.fromBase(16).equals(BaseSystem.HEXADECIMAL);   // true

The letters R understands after 0 come from the prefix registry: b 2, t 3, q 4, f 5, s 7, o 8, d 12, x 16, v 20, u 36, m 60, y 64; 0z[n] names any base. BaseSystem.registerPrefix adds your own.

Balanced, negative and bijective bases

Digits need not start at 0, and the radix need not be positive. In balanced ternary the digits are −1,0,1-1, 0, 1 (written T 0 1) and every integer, negative or not, has one spelling with no sign:

−5=(−1)⋅32+1⋅3+1=T11 bal3. -5 = (-1)\cdot 3^2 + 1\cdot 3 + 1 = \texttt{T11}_{\,\text{bal}3}.

In negabinary (radix −2-2) the place values alternate in sign, 1,−2,4,−8,…1, -2, 4, -8, \ldots, so again no minus sign is needed: −5=1−2+4−8=1111−2-5 = 1 - 2 + 4 - 8 = \texttt{1111}_{-2}.

const balanced = new BaseSystem("T01", "Balanced ternary", { radix: 3, digitOffset: -1 });
const negabinary = new BaseSystem("01", "Negabinary", { radix: -2 });
balanced.fromDecimal(-5n);       // "T11"
negabinary.fromDecimal(-5n);     // "1111"

These BaseSystems convert integers. For fractions in such bases, use NumeralSystem.

Roman numerals

BaseSystem.ROMAN is not a place-value base: a symbol's worth does not depend on its position, except that a smaller symbol written before a larger one is subtracted (IV=5−1\texttt{IV} = 5 - 1, XC=100−10\texttt{XC} = 100 - 10). It reads and writes the standard form for 1 to 3999, accepts lower case, and refuses spellings like IIII, IC or VX. There is no zero and no fractional digits, so a fraction comes out as a ratio of numerals.

BaseSystem.ROMAN.fromDecimal(1994n);         // "MCMXCIV" = 1000 + (1000 − 100) + (100 − 10) + (5 − 1)
BaseSystem.ROMAN.toDecimal("xiv");           // 14n
new Rational(3, 4).toBase(BaseSystem.ROMAN); // "III/IV"
R.base(BaseSystem.ROMAN)`XIV + II`;          // 16

NumeralSystem: exact, bounded, explained

new NumeralSystem({ kind, radix, tokens }) supports four kinds: ordinary, multiToken (digits that are words), balanced and negative. parse returns an exact Rational; format(q, { maxDigits }) expands with a work budget, and if the budget runs out it says so (status: "budgetExhausted", spelling: null) rather than returning a rounded answer.

import { NumeralSystem, Rational } from "@ratmath/core";

const words = new NumeralSystem({ kind: "multiToken", radix: 3, tokens: ["zero", "one", "two"] });
words.parse("onezero.two").toString();          // "11/3"
const bal = new NumeralSystem({ kind: "balanced", radix: 3, tokens: ["T", "0", "1"] });
bal.format(new Rational(1, 2)).spelling;        // "1.#T": 1 − 1/3 − 1/9 − … = 1/2
const dec = new NumeralSystem({ radix: 10, tokens: [..."0123456789"] });
dec.format(new Rational(1, 97), { maxDigits: 3 }).status;   // "budgetExhausted"

Each step of an expansion is recorded with exact remainders (rafter=b rbefore−dr_{\text{after}} = b\,r_{\text{before}} - d), places(text) lists each digit's exact weight and contribution, and locale converts to and from grouped forms such as 12 345,6#7.

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