Skip to content

Rational

ErikHaag edited this page Dec 29, 2022 · 9 revisions

Rational

Constructor

These arguments must be BigInts

Numerator

The numerator of the fraction.

Denominator

the denominator of the fraction, can't be less than 1. (default is 1)

let fraction1 = new Rational(4n); // fraction1 is 4/1

let fraction2 = new Rational(5n,3n); // fraction2 is 5/3

Methods

toLatex

returns the latex string corresponding to this

let frac = new Rational(5n, 2n);
console.log(frac.toLatex()); // "\frac{5}{2}"`

clone

returns a copy of this so you can manipulate the copy without affecting the original.

let frac = new Rational(5n,2n);
let copy= frac.clone();
copy.mult(new Rational(2n));
console.log(frac.value() == copy.value()); //false

cloneInverse

like clone, but it also flips the Rational.

let frac = new Rational(10n, 3n);
let inverse = frac.cloneInverse(); // inverse is 3/10

simplify

simplifies the rational it applies to, you don't need to use this as almost every function calls this one.

let frac = new Rational(1n)
frac.numerator = 10n;
frac.denominator = 4n;
console.log(frac.toLatex()); // "\frac{10}{4}"
frac.simplify();
console.log(frac.toLatex()); // "\frac{5}{2}"

value

returns a Number that the Rational represents

let frac = new Rational(5n, 2n); console.log(frac.value()); // 2.5

Note on comparisons

for small numerators and denominators, using .value() is fine; but if you are adding rationals together; it'll get imprecise in a hurry.

 if (frac1.value() < frac2.value()) {
     // do something
 }

try this:

 if (frac1.numerator * frac2.denominator < frac1.denominator * frac2.numerator) {
     // do something
 }

add, sub, mult, and div

these functions act like assignment operators, but for Rationals.

let frac1 = new Rational(4n, 5n);
let frac2 = new Rational(3n, 4n);
frac1.add(frac2); // frac1 += frac2;
console.log(frac1.toLatex()); // "\frac{31}{20}"
console.log(frac2.toLatex()); // "\frac{3}{4}"

pow

repeated multiplication, only accepts BigInts to avoid radicals.

let frac = new Rational(5n,3n);
frac.pow(3n);
console.log(frac.toLatex()); // "\frac{125}{27}"

Clone this wiki locally