欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java数学表达式计算(Expression Evaluator)

程序员文章站 2022-05-01 09:40:11
...
常见的表达式计算lib有:


(1)parsii
String exp = "2 + (7-5) * 3.14159 * x + sin(0)";

// compile
Scope scope = Scope.create();
Expression parsiiExpr = Parser.parse(exp);
Variable var = scope.getVariable("x");
var.setValue(X_VALUE);

// evaluate
double result = parsiiExpr.evaluate();

System.out.println(result);//-> 2.0


(2)JEval
String exp = "2 + (7-5) * 3.14159 * #{x} + sin(0)";

// compile
Evaluator jevalEvaluator = new Evaluator();
jevalEvaluator.setVariables(Collections.singletonMap("x", Double.toString(X_VALUE)));

// evaluate
double result = Double.parseDouble(jevalEvaluator.evaluate(exp));

System.out.println(result);//-> 2.0


(3)JEPLite
String exp = "2 + (7-5) * 3.14159 * x + sin(0)";

// compile
JEP jep = new JEP();
jep.addVariable("x", X_VALUE);
jep.parseExpression(exp);
DoubleStack jepStack = new DoubleStack();

// evaluate
double result = jep.getValue(jepStack);

System.out.println(result);//-> 2.0


http://andreas.haufler.info/2013/12/how-to-write-one-of-fastest-expression.html
http://www.transylvania-jug.org/archives/5777