I need to work with rationals in Javascript that have a denominator of 1. So, I have some input value, say 1024, and I need to store it as 1024/1. Of course 1024 / 1
just gives me 1024. So how can I obtain the raw rational version?
Asked
Active
Viewed 52 times
0

ChrisM
- 2,128
- 1
- 23
- 41
-
I think this package might be helpful: https://www.npmjs.com/package/rationals – jianweichuah Nov 20 '15 at 19:22
1 Answers
0
What are you looking to do with the rationals? If it's just for simple arithmetic you could just write it yourself.
Below is an example, you would do something similar for the other operators.
Hope this helps
function Rational(n, d) {
this.n = n;
this.d = d;
}
Rational.prototype.multiply = function(other) {
return this.reduce(this.n * other.n, this.d * other.d)
}
Rational.prototype.reduce = function(n, d) {
//http://stackoverflow.com/questions/4652468/is-there-a-javascript-function-that-reduces-a-fraction
var gcd = function gcd(a,b){
return b ? gcd(b, a%b) : a;
};
gcd = gcd(n,d);
return new Rational(n/gcd, d/gcd);
}
var r1 = new Rational(1, 2);
var r2 = new Rational(24, 1);
var result = r1.multiply(r2);
console.log(result); // Rational(12, 1);
console.log(result.n + '/' + result.d); // 12/1

luanped
- 3,178
- 2
- 26
- 40