Question
I use JEXL library to compute math expression with different arguments (for example y=2x+a^2-4*a*x where (x=1&a=3), (x=5&a=-15), etc). It works good on simple expressions, but when I start to use more hard expressions - it doesn't work. Here is code working well:
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!
but this one print wrong 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!
What I do wrong?
Solution
^
is bitwise xor, so 6 is the expected answer. See JEXL syntax for details.
OTHER TIPS
You can do something like that:
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());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow