Skip to content

Commit

Permalink
Fraction.divide tweak
Browse files Browse the repository at this point in the history
Chris Ward provided this useful suggestion about the Fraction.divide
code:

"(a/b)/(c/d) == (a/b)*(d/c).
Instead of using expensive division operations, and commonly converting
one or both of the numerator and denominator into floats, simply invert
the divisor and call the multiply function."

I implemented the change and was happy to find an approximate 2.5x speedup
in division operations and an end to common rounding errors which had
plagued the implementation.

Thanks Chris!
  • Loading branch information
ekg committed Feb 11, 2010
1 parent 6d3e79e commit 6549554
Showing 1 changed file with 3 additions and 5 deletions.
8 changes: 3 additions & 5 deletions fraction.js
Expand Up @@ -201,23 +201,21 @@ Fraction.prototype.multiply = function(b)
return a.normalize();
}


Fraction.prototype.divide = function(b)
{
var a = this.clone();
if (b instanceof Fraction)
{
a.numerator /= b.numerator;
a.denominator /= b.denominator;
a.numerator *= b.denominator;
a.denominator *= b.numerator;
} else if (typeof b === 'number') {
a.numerator /= b;
a.denominator *= b;
} else {
return a.divide(new Fraction(b));
}
return a.normalize();
}


Fraction.prototype.equals = function(b)
{
if (!(b instanceof Fraction)) {
Expand Down

0 comments on commit 6549554

Please sign in to comment.