exp4j is capable of evaluating simple expressions and functions. It's a lightweight library only ~30kB in size and without any external dependencies, that implements Dijkstra's Shunting Yard Algorithm.
check these links for some more info on exp4j:
Calculable calc = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
.withVariable("x", varX)
.withVariable("y", varY)
.build()
double result1=calc.calculate();One has to make sure that the variable names are passed into the ExpressionBuilder before calling build(). If variables are used in the expression without setting at least their names, an UnparseableErpessionExcetion will be thrown. The following three examples demonstrate the different possibilities to have exp4j recognize variables:
Using ExpressionBuilder.withVariableNames():
Calculable calc = new ExpressionBuilder("x * y - 2")
.withVariableNames("x","y")
.build();
calc.setVariable("x",1);
calc.setVariable("y",2);
assertTrue(calc.calculate()==0);Using implicit variable declarations in the expression string using e.g. "f(x,y)":.
Calculable calc = new ExpressionBuilder("f(x,y)=x * y - 2")
.build();
calc.setVariable("x",1);
calc.setVariable("y",2);
assertTrue(calc.calculate()==0);Using ExpresionBuilder.withVariable():
Calculable calc = new ExpressionBuilder("x * y - 2")
.withVariable("x",1);
.withVariable("y",2);
.build();
assertTrue(calc.calculate()==0);you can extend the abstract class CustomFunction in order to use custom functions in expressions. you only have to implement the applyFunction(double[] values) method.
CustomFunction fooFunc = new CustomFunction("foo") {
public double applyFunction(double[] values) {
return values[0]*Math.E;
}
};
double varX=12d;
Calculable calc = new ExpressionBuilder("foo(x)")
.withCustomFunction(fooFunc)
.withVariable("x",varX)
.build();
assertTrue(calc.calculate() == Math.E * varX);you can also define multi argument functions like max(a,b,c) via the constructor CustomFunction(String name,int argc), with argc being the argument count.
CustomFunction custom1 = new CustomFunction("max",3) {
@Override
public double applyFunction(double[] values) {
double max=values[0];
for (int i=1;i<this.getArgumentCount();i++) {
if (values[i] > max) {
max=values[i];
}
}
return max;
}
};
double varX=Math.E;
Calculable calc = new ExpressionBuilder("max(log(x),sin(x),x)")
.withVariable("x", varX)
.withCustomFunction(custom1)
.build();
assertTrue(varX == calc.calculate());Please let me know if you're project uses exp4j and you want it listed here