我使用 JEXL计算具有不同参数的数学表达式的库(例如 y=2x+a^2-4*a*x where (x=1&a=3), (x=5&a=-15), 等等)。它适用于简单的表达式,但当我开始使用更难的表达式时 - 它不起作用。这是运行良好的代码:
JexlEngine jexl = new JexlEngine();
Expression func = jexl.createExpression("x1+x2");
MapContext mc = new MapContext();
mc.set("x1", 2);
mc.set("x2", 1);
System.out.println(func.evaluate(mc)); // prints "3" - GOOD ANSWER!
但是这个打印错了答案:
JexlEngine jexl = new JexlEngine();
Expression func = jexl.createExpression("(x1-2)^4+(x1-2*x2)^2");
MapContext mc = new MapContext();
mc.set("x1", 2);
mc.set("x2", 1);
System.out.println(func.evaluate(mc)); // prints "6" - WRONG ANSWER!
我做错了什么?
最佳答案
你可以这样做:
Map<String, Object> functions=new HashMap<String, Object>();
// creating namespace for function eg. 'math' will be treated as Math.class
functions.put( "math",Math.class);
JexlEngine jexl = new JexlEngine();
//setting custom functions
jexl.setFunctions( functions);
// in expression 'pow' is a function name from 'math' wich is Math.class
Expression expression = jexl.createExpression( "math:pow(2,3)" );
expression.evaluate(new MapContext());
关于java - 为什么jexl calc算术错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8284059/