Using the ExpressionBuilder and the Calculable interface
Evaluate an expression
Calculable calc = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)").withVariable("x", varX).withVariable("y", varY).build()
double result1=calc.calculate();
you can also change variables values after building by invoking Calculable.setVariable(String varName,double value)
,
but one has to make sure that the variable names are passed into the ExpressionBuilder using at
least ExpressionBuilder.withVariableNames(String...). If variables are used in the expression without setting at least their names,
an UnparseableExpressionException will be thrown.
Calculable calc = new ExpressionBuilder("x * y - 2").withVariableNames("x","y").build();
calc.setVariable("x",1);
calc.setVariable("x",2);
assertTrue(calc.calculate()==0);
Using custom functions
you can extend the abstract class CustomFunction in order to use custom functions in expressions. You only have to implement the
applyFunction(double value) method.
CustomFunction fooFunc = new CustomFunction("foo") {
public double applyFunction(double value) {
return value*Math.E;
}
};
double varX=12d;
Calculable calc = new ExpressionBuilder("foo(x)").withCustomFunction(fooFunc).withVariable("x",varX).build();
assertTrue(calc.calculate() == Math.E * varX);
Using custom operators
you can extend the abstract class CustomOperator in order to use your own operators in expressions. You only have to implement the
applyOperation(double value) method. CustomOperator's constructor takes four arguments:
- the operator's symbols as a String
- whether the operator is left associative as a boolean
- the precedence of the operator as an int
- the number of operands for the operation
CustomOperator greaterEq = new CustomOperator(">=", true, 4, 2) {
double applyOperation(double[] values) {
if (values[0] >= values[1]){
return 1d;
}else{
return 0d;
}
}
};
Calculable calc = new ExpressionBuilder("1>=2").withOperation(greaterEq).build();
assertTrue(0d == calc.calculate());
Operators and functions
the following operators are supported:
- Addition: '2 + 2'
- Subtraction: '2 - 2'
- Multiplication: '2 * 2'
- Division: '2 / 2'
- Exponential: '2 ^ 2'
- Unary Minus,Plus (Sign Operators): '+2 - (-2)'
- Modulo: '2 % 2'
the following functions are supported:
- abs: absolute value
- acos: arc cosine
- asin: arc sine
- atan: arc tangent
- cbrt: cubic root
- ceil: nearest upper integer
- cos: cosine
- cosh: hyperbolic cosine
- exp: euler's number raised to the power (e^x)
- floor: nearest lower integer
- log: logarithmus naturalis (base e)
- sin: sine
- sinh: hyperbolic sine
- sqrt: square root
- tan: tangent
- tanh: hyperbolic tangent