UNPKG

2.75 kBMarkdownView Raw
1<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
2
3# Function simplify
4
5Simplify an expression tree.
6
7A list of rules are applied to an expression, repeating over the list until
8no further changes are made.
9It's possible to pass a custom set of rules to the function as second
10argument. A rule can be specified as an object, string, or function:
11
12 const rules = [
13 { l: 'n1*n3 + n2*n3', r: '(n1+n2)*n3' },
14 'n1*n3 + n2*n3 -> (n1+n2)*n3',
15 function (node) {
16 // ... return a new node or return the node unchanged
17 return node
18 }
19 ]
20
21String and object rules consist of a left and right pattern. The left is
22used to match against the expression and the right determines what matches
23are replaced with. The main difference between a pattern and a normal
24expression is that variables starting with the following characters are
25interpreted as wildcards:
26
27- 'n' - matches any Node
28- 'c' - matches any ConstantNode
29- 'v' - matches any Node that is not a ConstantNode
30
31The default list of rules is exposed on the function as `simplify.rules`
32and can be used as a basis to built a set of custom rules.
33
34For more details on the theory, see:
35
36- [Strategies for simplifying math expressions (Stackoverflow)](https://stackoverflow.com/questions/7540227/strategies-for-simplifying-math-expressions)
37- [Symbolic computation - Simplification (Wikipedia)](https://en.wikipedia.org/wiki/Symbolic_computation#Simplification)
38
39 An optional `options` argument can be passed as last argument of `simplify`.
40 There is currently one option available: `exactFractions`, a boolean which
41 is `true` by default.
42
43
44## Syntax
45
46```js
47simplify(expr)
48simplify(expr, rules)
49simplify(expr, rules)
50simplify(expr, rules, scope)
51simplify(expr, rules, scope, options)
52simplify(expr, scope)
53simplify(expr, scope, options)
54```
55
56### Parameters
57
58Parameter | Type | Description
59--------- | ---- | -----------
60`expr` | Node &#124; string | The expression to be simplified
61`rules` | Array&lt;{l:string, r: string} &#124; string &#124; function&gt; | Optional list with custom rules
62
63### Returns
64
65Type | Description
66---- | -----------
67Node | Returns the simplified form of `expr`
68
69
70## Examples
71
72```js
73math.simplify('2 * 1 * x ^ (2 - 1)') // Node "2 * x"
74math.simplify('2 * 3 * x', {x: 4}) // Node "24"
75const f = math.parse('2 * 1 * x ^ (2 - 1)')
76math.simplify(f) // Node "2 * x"
77math.simplify('0.4 * x', {}, {exactFractions: true}) // Node "x * 2 / 5"
78math.simplify('0.4 * x', {}, {exactFractions: false}) // Node "0.4 * x"
79```
80
81
82## See also
83
84[derivative](derivative.md),
85[parse](parse.md),
86[eval](eval.md),
87[rationalize](rationalize.md)