UNPKG

1.37 kBJavaScriptView Raw
1// algebra
2//
3// math.js has support for symbolic computation (CAS). It can parse
4// expressions in an expression tree and do algebraic operations like
5// simplification and derivation on this tree.
6
7// load math.js (using node.js)
8var math = require('../index');
9
10// simplify an expression
11console.log('simplify expressions');
12console.log(math.simplify('3 + 2 / 4').toString()); // '7 / 2'
13console.log(math.simplify('2x + 3x').toString()); // '5 * x'
14console.log(math.simplify('2 * 3 * x', {x: 4}).toString()); // '24'
15console.log(math.simplify('x^2 + x + 3 + x^2').toString()); // '2 * x ^ 2 + x + 3'
16console.log(math.simplify('x * y * -x / (x ^ 2)').toString()); // '-y'
17
18// work with an expression tree, evaluate results
19var f = math.parse('2x + x');
20var simplified = math.simplify(f);
21console.log(simplified.toString()); // '3 * x'
22console.log(simplified.eval({x: 4})); // 12
23console.log()
24
25// calculate a derivative
26console.log('calculate derivatives');
27console.log(math.derivative('2x^2 + 3x + 4', 'x').toString()); // '4 * x + 3'
28console.log(math.derivative('sin(2x)', 'x').toString()); // '2 * cos(2 * x)'
29
30// work with an expression tree, evaluate results
31var h = math.parse('x^2 + x');
32var dh = math.derivative(h, 'x');
33console.log(dh.toString()); // '2 * x + 1'
34console.log(dh.eval({x: 3})); // '7'