2

I've been searching google for a while now but can't find what I need. I need an open source mathematical expression parser & evaluator - of which there are a myriad - But one which links to a decent math library like Apache Commons Math. I need complex arithmetic, basic functions like sin, log that work on complex plane, and functions like gamma, erf.

The closest answer I found was Built-in method for evaluating math expressions in Java - but I couldn't see how, other than writing countless helper functions, to bind

  • jexpr
  • jruby
  • jeval
  • javax.script

with Commons math. Also it would take quite some work to modify my own existing (real-valued) expression parser to bind all the functions.

Plus, including a whole scripting programming language like python/ruby in my app seems overkill, where what I want to do is barely more than an old-fashioned pocket calculator.

Hasn't someone done this sort of thing already? Thanks!

Community
  • 1
  • 1
Sanjay Manohar
  • 6,920
  • 3
  • 35
  • 58

2 Answers2

2

You may want to check out an implementation that I created:

https://github.com/uklimaschewski/EvalEx.

It is based on java.math.BigDecimaland supports the basic matehmatical and boolean operations. It is a very compact implementation: only a single class file without any dependencies to other libraries. Plus, it can be easily extended with custom functions and operators.

Your gamma(1.8) example can be added in this way:

Expression e = new Expression("gamma(1.8)");

e.addFunction(e.new Function("gamma", 1) {
    @Override
    public BigDecimal eval(List<BigDecimal> parameters) {
        BigDecimal gamma = MyMathLibraryGammaCalculation(parameters.get(0));
        return gamma;
    }
});

e.eval(); // returns gamma(1.8)
Udo Klimaschewski
  • 5,150
  • 1
  • 28
  • 41
0

We used to do this with ScriptEngine for javascript - Not sure if that is sufficient for your requirements... here is a reference in SA:

Is there an eval() function in Java?

Community
  • 1
  • 1
Manidip Sengupta
  • 3,573
  • 5
  • 25
  • 27
  • Thanks for the fast answer. But I'm not sure that really works for my purpose - unless I missed something. I have written my own parsers that do most of what I need, but the work is in the linking with good math libraries and complex arithmetic operators, and linking with a standard function library. The idea is that users will be able to write `gamma(1.8)` and it will know to direct the function to the math library. – Sanjay Manohar Mar 10 '13 at 08:30