Two methods for cleaning/simplifying expressions are possible, the basic ExpressionCleaner is good for cleaning up expressions, removing unnecessary operations like addition of zero. Typically this may be used following differentiation which tends to create many such operations.
The more advanced Polynomial Simplification routines will reduce all polynomials to their simplest form and can be used on any expression. It can also compare expressions and extract polynomial coefficients.
The com.singularsys.extensions.xjep.ExpressionCleaner class offers routines to clean redundant parts of expressions:
Jep jep = new Jep(); jep.setComponent(new TreeUtils()); ExpressionCleaner cleaner = new ExpressionCleaner(); jep.setComponent(cleaner); Node node=jep.parse("1*x^1+0"); jep.println(node); Node cleaned=cleaner.clean(node); jep.println(cleaned);
which produces the output
1.0*x^1.0+0.0 x
Note how redundant parts of the equation like addition by zero, multiplication
by 1 and raising to the power of one are removed from the equation. Any constant
expressions like 1+2*3*cos(0)
will also be cleaned (in this case
giving 7
).
Actions: the ExpressionCleaner performs the following actions (here x
stands for
any sub-expression):
Source | Cleaned | Source | Cleaned |
---|---|---|---|
0+x | x |
x+0 | x |
x-0 | x | ||
1*x | x |
x*1 | x |
0*x | 0 |
x*0 | 0 |
-1*x | -x |
x*-1 | -x |
-(-x) | x | ||
x/1 | x | ||
x^0 | 1 |
x^1 | x |
0^x | 0 |
1^x | 1 |
2+(3+x) | 5.0+x |
(2+x)+3 | 5.0+x |
(3+x)*2 | 6.0+2.0*x |
3*(2-x) | 6.0-3.0*x |
1+(4*(3+(x/2))) | 13.0+2.0*x |
((3+(x/2))*4)+1 | 13.0+2.0*x |
A more extensive set of examples can be found in the com.singularsys.exttests.CleanerTest JUnit test.
The above examples uses a Jep instances with an additional TreeUtils component, this performs some tests on the type and value of a node. An alternate construction pattern would be to use
Jep jep = new Jep(); ExpressionCleaner cleaner = new ExpressionCleaner(jep, new TreeUtils(jep.getNumberFactory()));
The XJep sub-class of Jep binds together various symbolics facility and make construction simple. Using this class the above example becomes
XJep xjep = new XJep(); Node node = xjep.parse("1*x^1+0"); xjep.println(node); Node cleaned = xjep.clean(node); xjep.println(cleaned);
See the XJep documentation page for details.