rational numbers with operations
Why I think this lib is great:
Representing fractions is not just easy, but it's natural. This is what
rational numbers do best. Operations like
0.1 + 0.2 are a pain in js,
but using rational numbers, it's just:
r(1,10).plus(1,5) === r(3,10)
This lib provides a type of object which will work with 1/0 or 0/0 just as well. This is especially useful if you plan to plot values on a graph.
I've got the inspiration for this lib from here: MF105: The extended rational numbers in practice
var r = require('rationals');// denominator of 1 is optionalr(1) === r(1); // truer(1,1) === r(1); // true// all rationals will be always reducedr(2,4) === r(13,26); // truer(100,50) === r(2); // true// chaining worksr(1,2).plus(r(1,3)).minus(r(1,4)).times(r(1,5)).per(r(1,6)) === r(49,70); // true// my personal favorite aproximation of Pi, from ancient chinar(355,113).val(); // 3.1415929203539825// you can give floats and they will be converted into rationalsrats(0.4,0.1) == rats(4);
subtract (minus, sub)
multiply (times, mul)
divide (per, div)
Examining an object can be hard, but if you cast it to a string:
r(355,113)+'' will return
r(625,125).toString() will return
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.
Will return -1, 0 or 1 if the rational is smaller, equal or larger than the rational it is compared to
r(-999,605).compare(R(272,835)) // -1
r(-966,743).compare(R(-632,198)) // 1
r(-3,9).compare(R(12,-36)) // 0
Same as compare but without signs.
r(-999,605).compareAbs(R(272,835)) // 1
If you provide anything else as the numerator, than an integer, float or a numerica string an exception will be thrown. On the other hand, if you do the same with the denominator, it will be cast to 1. This is because I am lazy, and I do not want to handle wrong values and undefined values differently throwing for the former and casting to 1 for the latter.
npm install rationals
You can use it in the browser with browserify