UNPKG

1.28 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)
8const { simplify, parse, derivative } = require('..')
9
10// simplify an expression
11console.log('simplify expressions')
12console.log(simplify('3 + 2 / 4').toString()) // '7 / 2'
13console.log(simplify('2x + 3x').toString()) // '5 * x'
14console.log(simplify('2 * 3 * x', { x: 4 }).toString()) // '24'
15console.log(simplify('x^2 + x + 3 + x^2').toString()) // '2 * x ^ 2 + x + 3'
16console.log(simplify('x * y * -x / (x ^ 2)').toString()) // '-y'
17
18// work with an expression tree, evaluate results
19const f = parse('2x + x')
20const simplified = simplify(f)
21console.log(simplified.toString()) // '3 * x'
22console.log(simplified.evaluate({ x: 4 })) // 12
23console.log()
24
25// calculate a derivative
26console.log('calculate derivatives')
27console.log(derivative('2x^2 + 3x + 4', 'x').toString()) // '4 * x + 3'
28console.log(derivative('sin(2x)', 'x').toString()) // '2 * cos(2 * x)'
29
30// work with an expression tree, evaluate results
31const h = parse('x^2 + x')
32const dh = derivative(h, 'x')
33console.log(dh.toString()) // '2 * x + 1'
34console.log(dh.evaluate({ x: 3 })) // '7'