3

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?

Dmitry Belaventsev
  • 6,347
  • 12
  • 52
  • 75

2 Answers2

5

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());
Piotr Skoczek
  • 71
  • 1
  • 7
3

^ is bitwise xor, so 6 is the expected answer. See JEXL syntax for details.

Ben van Gompel
  • 747
  • 4
  • 12
  • You are right! Thx! So, how can I implement Math.pow() in JEXL? Or I should use another lib for my purposes? – Dmitry Belaventsev Nov 27 '11 at 09:01
  • @dizpers I've never used JEXL myself, so I cannot help you there. I'd suggest to look for examples on the internet. They (the JEXL community) also have mailing lists where you might get more answers. – Ben van Gompel Nov 27 '11 at 09:44