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

Added differentiation for expressions #83

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions src/expressions.js
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,32 @@ Expression.prototype.summation = function(variable, lower, upper, simplify) {
return newExpr;
};

Expression.prototype.diff = function(variable) {
var expr = this.copy();
expr.constants = [];
epxr = expr.simplify();

for (var i = 0; i < expr.terms.length; i++) {
var thisTerm = expr.terms[i];
var termIncludesVar = false;
for (var j = 0; j < thisTerm.variables.length; j++) {
var thisVar = thisTerm.variables[j];
if (thisVar.variable === variable) {
thisTerm.coefficients.push(new Fraction(thisVar.degree, 1));
thisVar.degree--;
if (thisVar.degree === 0 && thisTerm.variables.length === 1) {
expr.constants.push(new Fraction(1, 1));
expr.terms.splice(i, 1);
}
}
}
}

expr = expr.simplify();

return expr;
}

Expression.prototype.toString = function(options) {
var str = "";

Expand Down
42 changes: 42 additions & 0 deletions test/expression-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -859,3 +859,45 @@ describe("Expression summation", function() {
expect(answer.toString()).toEqual("4y + 30");
});
});

describe("Differentiation of expression", function() {
it("should use power rule", function () {
var exp = new Expression("x").pow(2);

var answer = exp.diff("x");

expect(answer.toString()).toEqual("2x");
});

it("should turn a single power variable of the chosen variable into 1", function () {
var exp = algebra.parse("x+x^2");

var answer = exp.diff("x");

expect(answer.toString()).toEqual("2x + 1");
});

it("should ignore other variables", function () {
var exp = algebra.parse("y+x^2");

var answer = exp.diff("x");

expect(answer.toString()).toEqual("2x + y");
});

it("should work for other varibles", function () {
var exp = algebra.parse("y+x^2");

var answer = exp.diff("y");

expect(answer.toString()).toEqual("x^2 + 1");
});

it("should work for products of main and other variables", function () {
var exp = algebra.parse("y*x");

var answer = exp.diff("x");

expect(answer.toString()).toEqual("y");
});
});