Topic

Rationals

A Rational is a fraction p/qp/q held as two BigInts, always in lowest terms with q>0q > 0. Sums, products and quotients of fractions are fractions, so nothing is ever rounded.

Lowest terms

Every constructor divides out g=gcd⁡(p,q)g = \gcd(p, q) and moves the sign to the numerator, so two equal values always have the same parts and equals is a comparison of two pairs of integers. Arithmetic uses the schoolbook rules and reduces again:

ab+cd=ad+bcbd,ab⋅cd=acbd,ab÷cd=adbc. \frac{a}{b} + \frac{c}{d} = \frac{ad + bc}{bd}, \qquad \frac{a}{b}\cdot\frac{c}{d} = \frac{ac}{bd}, \qquad \frac{a}{b} \div \frac{c}{d} = \frac{ad}{bc}.
import { Rational } from "@ratmath/core";

new Rational(6, -8).toString();            // "-3/4"
new Rational("2..1/3").toString();         // "7/3" (mixed number)
new Rational("0.#3").toString();           // "1/3" (repeating decimal)
const x = new Rational(2, 3);
x.add(new Rational(5, 6)).toString();      // "3/2"
x.pow(-2).toString();                      // "9/4"
x.E(3).toString();                         // "2000/3", times 10^3
x.lessThan(new Rational(3, 4));            // true

A string argument may be any number literal (integer, fraction, mixed number, decimal, repeating decimal); a second argument divides it, so new Rational("3/4", 5) is 320\tfrac{3}{20}. Number arguments must be safe integers.

Repeating decimals

Every fraction has a decimal expansion that ends or repeats forever. RatMath writes the repeating block after a #: 16=0.16‾\tfrac16 = 0.1\overline{6} is 0.1#6, and 17\tfrac17 is 0.#142857. Both directions are exact: parseDecimal("0.1#6") gives back 16\tfrac16.

Why it repeats: long division of pp by qq only ever has remainders 0,1,…,q−10, 1, \ldots, q-1, so within qq steps a remainder comes back and the digits cycle from there. Write q=2a5bmq = 2^a 5^b m with gcd⁡(m,10)=1\gcd(m, 10) = 1. Then the expansion has max⁡(a,b)\max(a, b) digits before the period, and the period length is the order of 10 modulo mm: the least kk with

10k≡1(modm). 10^k \equiv 1 \pmod m.

The decimal ends exactly when m=1m = 1. For 17\tfrac17, 106=142857⋅7+110^6 = 142857 \cdot 7 + 1, so the period is 6. Going back is a geometric series: a block BB of kk digits repeating forever is B/(10k−1)B/(10^k - 1), which is why 0.#9 is exactly 1.

const sixth = new Rational(1, 6);
sixth.toRepeatingDecimal();                // "0.1#6"
sixth.toRepeatingDecimalWithPeriod();      // { decimal: "0.1#6", period: 1, truncated: false }
new Rational(1, 97).toRepeatingDecimal(100);   // 96-digit period, limit raised to 100
new Rational(1, 97).toRepeatingDecimal(10, "trunc");   // "0.#0103092783..." (display only)

The default period limit is 30 digits (Rational.MAX_PERIOD_DIGITS). Past it, toRepeatingDecimal throws unless you pass a larger limit, or "trunc" for a display string ending in ..., which is deliberately not parseable. computeDecimalMetadata() returns the pieces (whole part, pre-period, period digits and length) for your own formatting.

Other written forms

method−9/4-9/4 givesexact?
toString()-9/4yes
toMixedString()-2..1/4yes
toRepeatingDecimal()-2.25#0 (a #0 marks the end)yes
toDecimal(digits = 20)-2.25display: cut after digits places
toScientificNotation()-2.25E0display
toNumber()-2.25a float: may round

Rounding

The default is school rounding, half up. A tie goes away from zero: 6.5 rounds to 7, 65 to the nearest ten is 70, and −2.5-2.5 rounds to −3-3. Banker's rounding is the mode "half-even", where a tie goes to the even neighbour (6.5 to 6, 7.5 to 8): new Rational(65).roundTo(-1, "half-even") is 60. Statistics and accounting often prefer it because it has no bias when many rounded values are summed. (Before 0.12.0 the default was half-even.)

floor(), ceil(), trunc() and round(mode) return a Core Integer, so the result goes straight into further arithmetic; its bigint is .value and a JavaScript number is .toNumber(). (Before 0.12.0 they returned bigints.) roundTo(places, mode) returns a Rational with at most that many decimal places; a negative places rounds to tens, hundreds and so on. Modes are half-up (the default; ties go away from zero, so −5/2-5/2 rounds to −3-3), half-even (banker's rounding), toward-zero (truncate), floor (toward −∞-\infty) and ceil (toward +∞+\infty). Because the value is exact, ties are decided correctly even when a float cannot see them: the decimal 2.6752.675 is a tie to two places, but the nearest double is 2.67499999…2.67499999\ldots, so floats round it down.

Other conventions. ROUNDING_MODES lists every name: half-up, half-down (ties toward zero), half-even, half-odd, half-ceil (ties toward +∞+\infty), half-floor (ties toward −∞-\infty), floor, ceil, toward-zero and away-from-zero. rounding(mode) makes a rounder for one convention that you can keep and pass around: r(x) gives the Integer and r(x, places) rounds to decimal places. A rounder is a value, not a global setting, so choosing banker's rounding in one place never changes another library's results.

For a convention of your own, pass a function instead of a name. It is called only for a value that is not already an integer, with { value, floor, ceil, fraction } where fraction is value − floor, and it must return floor or ceil. With places, value is measured in units of the last place.

const bankers = rounding("half-even");
bankers(R`6.5`);                     // Integer 6
bankers(R`2.675`, 2);                // 2.68: a true tie, so to the even digit
const generous = rounding(({ floor, ceil, fraction }) =>
  fraction.lessThan(new Rational(7, 10)) ? floor : ceil);   // up only from .7
generous(R`6.65`);                   // Integer 6
new Rational(7, 2).round("half-odd");  // Integer 3
const t = new Rational(5, 2);
[t.floor(), t.ceil(), t.round(), t.round("half-even")]; // Integers 2, 3, 3, 2
t.round().multiply(new Integer(10));                    // Integer 30
t.floor().value;                                        // 2n
new Rational(65).roundTo(-1);                           // 70 (school rounding)
new Rational(65).roundTo(-1, "half-even");              // 60 (banker's rounding)
new Rational(2, 3).roundTo(3).toString();               // "667/1000"

Digits and place value

digitAt(k, base = 10) is the digit in place kk of ∣x∣|x|: k=0k = 0 is the ones place, 1 the tens, −1-1 the tenths. placeValue(k) is what that digit is worth, with the number's sign. Both are exact for every rational, repeating expansions included. Integers also have digits(base), most significant first.

new Integer(486).placeValue(1);          // 80: the 8 in 486 is eight tens
new Integer(486).digits();               // [4, 8, 6]
new Rational(347, 100).placeValue(-2);   // 7/100
new Rational(1, 7).digitAt(-3);          // 2 (0.142857...)
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