为什么jexl计算算法错误

Dmi*_*sev 3 java jexl

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

但这一个打印错误答案:

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!
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

小智 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());
Run Code Online (Sandbox Code Playgroud)