Java Expression Parser & Evaluator

There are quite a lot of free and commercial expression evaluators for Java out there.
From simple to complicated, you have a lot of choices.

But when I needed one the other day, it was quickly clear that none of the existing solutions fitted exactly my needs.

First of all, it had to understand decimal and also negative values. You would be surprised to see how many of the existing solutions do not support that. The reason for this lack of support, by the way, is IMHO the lack of public available general tokenizing algorithms.
Solving expression like `1+(6-4)*5` is easy, when you have access to Google and/or Wikipedia, because it is a standard task in learning algorithms and data structures. When it comes to expressions like `1+(6 - -4.3)*-5.21`, things get a bit more tricky and require some homemade logic in advance.

Second feature, the solution had to be simple and compact. Ideally it would be only a single class without the need of additional external libraries. Small footprint and based on standard 1.6 Java runtime.

Third and most important feature was the need for Java `BigDecimal` support. Nearly all of the existing simple solutions use Java’s `double` as a base data type for calculations. I had no need for high precision in trigonometric or logarithmic functions, but a strong need for exact precision in normal arithmetic. You think normal Java `double` based arithmetic is enough for everything that is below rocket science? You are utterly wrong. Take a look at this code snippet that adds 0.1 tens times and prints each result:

```public static void main(String[] args) {
double x = 0;
for (int i = 0; i < 10; i ++) {
x = x + 0.1;
System.out.println("Value of x: " + x);
}
}
```

It will print out the following:
``` Value of x: 0.1 Value of x: 0.2 Value of x: 0.30000000000000004 Value of x: 0.4 Value of x: 0.5 Value of x: 0.6 Value of x: 0.7 Value of x: 0.7999999999999999 Value of x: 0.8999999999999999 Value of x: 0.9999999999999999 ```

This is not ‘wrong’, because of the limited possibilities to store fractional numbers in general.
Now, using Java double based arithmetic in a financial application should be considered harmful, from my point of view. At least if you are not extremely careful with rounding in every step. Therefore the need for BigDecimal support.

Fourth feature was the support for Boolean logic, ideally mixable with standard arithmetic. I wanted to be able to not only evaluate Boolean expressions like `x < 4 && y > 5`, but also expressions like `2 * x^2 > sqrt(y - 3.2) && max(x, 100) > 100`.

And last but not least, of course support for functions and variables, as seen in the examples above.

So I sat down and implemented one, that had all what I wanted, plus some more features I caught on the way:

• Uses BigDecimal for calculation and result
• Single class implementation, very compact
• No dependencies to external libraries
• Precision and rounding mode can be set
• Supports variables
• Standard Boolean and mathematical operators
• Standard basic mathematical and Boolean functions
• Custom functions and operators can be added at runtime

The complete source can be found on GitHub, which is in fact only a single Java file, if you remove all the JUnit test cases and administrative files like license and readme.

The class `com.udojava.evalex.Expression` is all you need to have this handy expression parser and evaluator up and running.

To work with it, simply create an expression by passing the expression string:

```Expression e = new Expression("1+1/3");
```

Then you can evaluate the expression by calling the eval() method on the expression:

```BigDecimal result = e.eval();
```

Once you have an expression, you can re-evaluate it again and again, possibly with adjusting parameters like variables, precision, rounding mode and even modified functions and operators:

```e.setPrecision(2);
e.setRoundingmode(RoundingMode.up);
BigDecimal result2 = e.eval();
```

A way of combining those actions, called chaining, is becoming more and more en vogue in Java and other programming languages. Java’s BigDecimal supports that pattern and my EvalExer also does:

```BigDecimal result = new Expression("1+1/3").setPrecision(3).setRoundingMode(RoundingMode.UP).eval();
```

Variables can be set on an expression in different ways and then the expression can be re-evaluated without creating a new expression every time:

```Expression e = new Expression("SQRT(a^2 + b^2)");
e.setVariable("a","3.42");
e.setVariable("b", new BigDecimal(9.6));
e.eval();
e.setVariable("a","9.51");
e.setVariable("b", new BigDecimal(8.4));
e.eval();
```

There are also some convenient methods for chaining expressions with variable setters:

```BigDecimal result = new Expressions("SQRT(a^2 + b^2)").with("a",new BigDecimal (3.42)).and("b2,"9,6").setPrecision(2).eval();
```

And, of course, with BigDecimal chaining combined, you can have more chaining fun:

```BigDecimal result = new Expressions("SQRT(a^2 + b^2)").with("a",new BigDecimal (3.42)).and("b","9,6").setPrecision(2).eval().add(14.2).divide(3);
```

Initially, the EvalEx parser/evaluator comes with a predefined set of operators and functions. (Plus a 100 digits exact predefined variable for `PI`, for free).

This set of operators, functions and variables can be extended at runtime without modifying the existing class.
Adding variables is easy, we have seen that before. Simply add them using the different chainable `set()/with()/and()` functions to an expression.

Custom operators can be added easily, simply create an instance of `Expression.Operator` and add it to the expression. Parameters are the operator name, its precedence and if it is left associative. The operators `eval()` method will be called with the `BigDecimal` values of the operands. All existing operators can also be overridden.
For example, add an operator `x >> n`, that moves the decimal point of `x` `n` digits to the right:

```Expression e = new Expression("2.1234 &gt;&gt; 2");

@Override
public BigDecimal eval(BigDecimal v1, BigDecimal v2) {
return v1.movePointRight(v2.toBigInteger().intValue());
}
});

e.eval(); // returns 212.34
```

Adding custom functions is as easy as adding custom operators. Create an instance of `Expression.Function` and add it to the expression. Parameters are the function name and the count of required parameters. The functions `eval()` method will be called with a list of the `BigDecimal` parameters. All existing functions can also be overridden.
For example, add a function `average(a,b,c)`, that will calculate the average value of a, b and c:

```Expression e = new Expression("2 * average(12,4,8)");

@Override
public BigDecimal eval(List parameters) {
return sum.divide(new BigDecimal(3));
}
});

e.eval(); // returns 16
```

Supported Operators

Mathematical Operators
Operator Description
Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator (Modulo)
^ Power operator
Boolean Operators*
Operator Description
= Equals
== Equals
!= Not equals
<> Not equals
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
&& Boolean and
|| Boolean or

*Boolean operators result always in a BigDecimal value of 1 or 0 (zero). Any non-zero value is treated as a _true_ value. Boolean _not_ is implemented by a function.

Supported Functions

Function* Description
NOT(expression) Boolean negation, 1 (means true) if the expression is not zero
RANDOM() Produces a random number between 0 and 1
MIN(e1,e2) Returns the smaller of both expressions
MAX(e1,e2) Returns the bigger of both expressions
ABS(expression) Returns the absolute (non-negative) value of the expression
ROUND(expression,precision) Rounds a value to a certain number of digits, uses the current rounding mode
LOG(expression) Returns the natural logarithm (base e) of an expression
SQRT(expression) Returns the square root of an expression
SIN(expression) Returns the trigonometric sine of an angle (in degrees)
COS(expression) Returns the trigonometric cosine of an angle (in degrees)
TAN(expression) Returns the trigonometric tangens of an angle (in degrees)
SINH(expression) Returns the hyperbolic sine of a value
COSH(expression) Returns the hyperbolic cosine of a value
TANH(expression) Returns the hyperbolic tangens of a value
RAD(expression) Converts an angle measured in degrees to an approximately equivalent angle measured in radians
DEG(expression) Converts an angle measured in radians to an approximately equivalent angle measured in degrees

*Functions names are case insensitive.

Supported Constants

Constant Description
PI The value of PI, exact to 100 digits