What's a good library for parsing mathematical expressions in java?

22,143

Solution 1

I wrote a simple but capable Math Expression Evaluator a while back, which is free and open-source. It's main advantage is being fast and tiny - both are a good thing with hand-held devices. If it meets your need you are welcome to use it.

Primary Features:

  • Basic math operators, with inferred precedence (^ * × · / ÷ % + -).
  • Explicit precedence with parenthesis.
  • Implicit multiplication of bracketed subexpressions.
  • Correct right-associativity of exponentials (power operator).
  • Direct support for hexadecimal numbers prefixed by 0x.
  • Constants and variables.
  • Extensible operators.
  • Extensible functions.
  • 20 KiB footprint.

Example

MathEval math=new MathEval();

math.setVariable("Top",    5);
math.setVariable("Left",  20);
math.setVariable("Bottom",15);
math.setVariable("Right", 60);

System.out.println("Middle: "+math.evaluate("floor((Right+1-Left)/2)"));

Solution 2

JEval is a good alternative. I abandoned Jep due to it becoming commercial. The only concern is that JEval seems to be a little dormant at the moment (last release in 2008).

Solution 3

Try https://code.google.com/p/expressionoasis/. It is an extensible Expression Evaluation framework and will meet such requirements.

Share:
22,143
CodeFusionMobile
Author by

CodeFusionMobile

I am an electrical engineering/computer scientist. I did my undergrad at South Dakota State University and am currently pursuing a Masters in Robotics at University of Pennsylvania. I have worked as a software developer at Daktronics, Inc, a scoreboard and stats company. I also am an independant Android developer.

Updated on July 09, 2022

Comments

  • CodeFusionMobile
    CodeFusionMobile almost 2 years

    I'm an Android Developer and as part of my next app I will need to evaluate a large variety of user created mathematical expressions and equations. I am looking for a good java library that is lightweight and can evaluate mathematical expressions using user defined variables and constants, trig and exponential functions, etc.

    I've looked around and Jep seems to be popular, but I would like to hear more suggestions, especially from people who have used these libraries before.

  • CodeFusionMobile
    CodeFusionMobile about 14 years
    Nice an small, but I'm afraid I need support for more advanced functions and expressions.
  • dreeves
    dreeves almost 14 years
    I tried this and it seems to work great. Nice and simple. Thanks!
  • adamdunson
    adamdunson over 10 years
    Your answer could be improved by listing some of the features of this library or, perhaps, by explaining how it compares to other existing libraries.
  • user207421
    user207421 about 7 years
    Not an answer unless the code is posted here.