Skip to content
This repository has been archived by the owner on May 23, 2019. It is now read-only.

Commit

Permalink
Fix order of operations when solving quadratics w irrational sltns
Browse files Browse the repository at this point in the history
When solving a quadratic equation where the solutions are irrational
and a > 1, an order of operation fail was multiplying the results by a
at the end instead of diving by 2a. :(

Fixes #39.
  • Loading branch information
nicolewhite committed Oct 20, 2015
1 parent 570f6b4 commit a84cb43
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/equations.js
Expand Up @@ -120,8 +120,8 @@ Equation.prototype.solveFor = function(variable) {
a = a.valueOf();
b = b.valueOf();

var root1 = (-b - squareRootDiscriminant) / 2*a;
var root2 = (-b + squareRootDiscriminant) / 2*a;
var root1 = (-b - squareRootDiscriminant) / (2*a);
var root2 = (-b + squareRootDiscriminant) / (2*a);
return [root1, root2];
}
}
Expand Down
13 changes: 13 additions & 0 deletions test/equation-spec.js
Expand Up @@ -116,6 +116,19 @@ describe("Solving a quadratic equation", function() {
expect(round(answers[1])).toEqual(round(expected[1]));
});

it("should get the right answer when the answers are irrational and a > 1", function() {
var lhs = x.pow(2).multiply(2);
lhs = lhs.add(x.multiply(2));
lhs = lhs.subtract(5);

var eq = new Equation(lhs, 0); // 2x^2 + 2x - 5 = 0
var answers = eq.solveFor("x");
var expected = [-1/2 - Math.sqrt(11)/2, Math.sqrt(11)/2 -1/2];

expect(round(answers[0])).toEqual(round(expected[0]));
expect(round(answers[1])).toEqual(round(expected[1]));
});

it("should return one reduced fraction if there's only one real root", function() {
var ex = x.multiply(x).add(x.multiply(2));
var eq = new Equation(ex, -1); // x^2 + 2x = -1
Expand Down

0 comments on commit a84cb43

Please sign in to comment.