public class MathematicalExpression extends java.lang.Object implements RevisionHandler
expr_list ::= expr_list expr_part | expr_part ; expr_part ::= expr ; expr ::= NUMBER | ( expr ) | opexpr | varexpr | funcexpr ; opexpr ::= expr + expr | expr - expr | expr * expr | expr / expr ; varexpr ::= VARIABLE ; funcexpr ::= abs ( expr ) | sqrt ( expr ) | log ( expr ) | exp ( expr ) | sin ( expr ) | cos ( expr ) | tan ( expr ) | rint ( expr ) | floor ( expr ) | pow ( expr , expr ) | ceil ( expr ) | ifelse ( boolexpr , expr (if true) , expr (if false) ) ; boolexpr ::= BOOLEAN | true | false | expr < expr | expr <= expr | expr > expr | expr >= expr | expr = expr | ( boolexpr ) | ! boolexpr | boolexpr & boolexpr | boolexpr | boolexpr ;Code example 1:
String expr = "pow(BASE,EXPONENT)*MULT"; HashMap symbols = new HashMap(); symbols.put("BASE", new Double(2)); symbols.put("EXPONENT", new Double(9)); symbols.put("MULT", new Double(0.1)); double result = MathematicalExpression.evaluate(expr, symbols); System.out.println(expr + " and " + symbols + " = " + result);Code Example 2 (uses the "ifelse" construct):
String expr = "ifelse(I<0,pow(BASE,I*0.5),pow(BASE,I))"; MathematicalExpression.TreeNode tree = MathematicalExpression.parse(expr); HashMap symbols = new HashMap(); symbols.put("BASE", new Double(2)); for (int i = -10; i <= 10; i++) { symbols.put("I", new Double(i)); double result = MathematicalExpression.evaluate(expr, symbols); System.out.println(expr + " and " + symbols + " = " + result); }
Constructor and Description |
---|
MathematicalExpression() |
Modifier and Type | Method and Description |
---|---|
static double |
evaluate(java.lang.String expr,
java.util.HashMap symbols)
Parses and evaluates the given expression.
|
java.lang.String |
getRevision()
Returns the revision string.
|
public static double evaluate(java.lang.String expr, java.util.HashMap symbols) throws java.lang.Exception
expr
- the expression to evaluatesymbols
- the symbol/value mappingjava.lang.Exception
- if something goes wrongpublic java.lang.String getRevision()
getRevision
in interface RevisionHandler