为什么jexl计算算法错误

时间:2011-11-27 06:36:19

标签: java jexl

我使用JEXL库来计算具有不同参数的数学表达式(例如,y = 2x + a ^ 2-4 * a * x其中(x = 1& a = 3),(x = 5& 3)。 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!

我做错了什么?

2 个答案:

答案 0 :(得分:5)

你可以这样做:

   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());

答案 1 :(得分:3)

^是按位xor,所以6是预期答案。有关详细信息,请参阅JEXL syntax