Basically, each rational number is reduced to normal form, then memoized so referential equation works, each instance of any rational number will === with any other instance of the same rational number, even if they were constructed using different inputs.
Of course, if you run out of memory, you run out of memory, but you knew that when you decided to use BigInt.
I've got the inspiration for this lib from here: MF105: The extended rational numbers in practice
import rat as R from rationals // denominator of 1 is optional R(1) === R(1); // true R(1,1) === R(1); // true // all rationals will be always reduced R(2,4) === R(13,26); // true R(100,50) === R(2); // true // my personal favorite aproximation of Pi, from ancient china R(355,113); // 3.1415929203539825 // you can give floats and they will be converted into rationals fromNumber(0.4,0.1) == rats(4);
- a & b are objects created with the rationals() function
- in the parentheses you have some common aliases for the methods
Examining an object can be hard, but if you cast it to a string:
Just like toString(), but the numerator will be shown only if it's not 1. That is, integers will appear without a slash symbol and a denominator.
Will return the numerator divided with the denominator. Note that this casts bigints to ints so whatever can happen.
Will return -1, 0 or 1 if the rational is smaller, equal or larger than the rational it is compared to
.compare(R(-999,605), R(272,835)) // -1
.compare(R(-966,743), R(-632,198)) // 1
.compare(R(-3,9), R(12,-36)) // 0
Compare absolute values
Same as compare but without signs.
.compare(R(-999,605), R(272,835)) // 1
npm install rationals
You can use it in the browser with browserify