Package weka.core
Class MathematicalExpression
java.lang.Object
weka.core.MathematicalExpression
- All Implemented Interfaces:
RevisionHandler
Class for evaluating a string adhering the following grammar:
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 invalid input: '&' 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(Iinvalid input: '<'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 invalid input: '<'= 10; i++) { symbols.put("I", new Double(i)); double result = MathematicalExpression.evaluate(expr, symbols); System.out.println(expr + " and " + symbols + " = " + result); }
- Version:
- $Revision: 4942 $
- Author:
- FracPete (fracpete at waikato dot ac dot nz)
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic double
Parses and evaluates the given expression.Returns the revision string.
-
Constructor Details
-
MathematicalExpression
public MathematicalExpression()
-
-
Method Details
-
evaluate
Parses and evaluates the given expression. Returns the result of the mathematical expression, based on the given values of the symbols.- Parameters:
expr
- the expression to evaluatesymbols
- the symbol/value mapping- Returns:
- the evaluated result
- Throws:
Exception
- if something goes wrong
-
getRevision
Returns the revision string.- Specified by:
getRevision
in interfaceRevisionHandler
- Returns:
- the revision
-