2017-08-06 13:46:55 +02:00

78 lines
2.2 KiB
Markdown

<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function simplify
Simplify an expression tree.
A list of rules are applied to an expression, repeating over the list until
no further changes are made.
It's possible to pass a custom set of rules to the function as second
argument. A rule can be specified as an object, string, or function:
var rules = [
{ l: 'n1*n3 + n2*n3', r: '(n1+n2)*n3' },
'n1*n3 + n2*n3 -> (n1+n2)*n3',
function (node) {
// ... return a new node or return the node unchanged
return node
}
]
String and object rules consist of a left and right pattern. The left is
used to match against the expression and the right determines what matches
are replaced with. The main difference between a pattern and a normal
expression is that variables starting with the following characters are
interpreted as wildcards:
- 'n' - matches any Node
- 'c' - matches any ConstantNode
- 'v' - matches any Node that is not a ConstantNode
The default list of rules is exposed on the function as `simplify.rules`
and can be used as a basis to built a set of custom rules.
For more details on the theory, see:
- [Strategies for simplifying math expressions (Stackoverflow)](http://stackoverflow.com/questions/7540227/strategies-for-simplifying-math-expressions)
- [Symbolic computation - Simplification (Wikipedia)](https://en.wikipedia.org/wiki/Symbolic_computation#Simplification)
## Syntax
```js
simplify(expr)
simplify(expr, rules)
simplify(expr, rules, scope)
simplify(expr, scope)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`expr` | Node &#124; string | The expression to be simplified
`rules` | Array&lt;{l:string, r: string} &#124; string &#124; function&gt; | Optional list with custom rules
### Returns
Type | Description
---- | -----------
Node | Returns the simplified form of `expr`
## Examples
```js
math.simplify('2 * 1 * x ^ (2 - 1)'); // Node {2 * x}
math.simplify('2 * 3 * x', {x: 4}); // Node {24}
var f = math.parse('2 * 1 * x ^ (2 - 1)');
math.simplify(f); // Node {2 * x}
```
## See also
[derivative](derivative.md),
[parse](parse.md),
[eval](eval.md)