exp4j is capable of evaluating expressions and functions in the real domain. It's a small (40KB) library without any external dependencies, that implements Dijkstra's Shunting Yard Algorithm. exp4j comes with a standard set of built-in functions and operators. Additionally users are able to create custom operators and functions.
As of Version 0.4.0 exp4j has been completely rewritten and a lot of API changes have been introduced. Please don't hate me ;). The old version is still available. Im currently planning to supply a legacy-pack with wrappers for the old API, but I'm not sure that it is feasible. The rewrite was IMHO necessary to accommodate various features (e.g. implicit multiplication) and first of all: Improved performance.
The former version of exp4j is available here
The examples are mostly taken from the test class ExpressionBuilderTest and use JUnit's assertXXX() methods to check for correct results.
In order to evaluate an expression. The ExpressionBuilder class can be used to create an Expression object which is capable of evaluation. Custom functions and custom operators can be set via calls to ExpressionBuilder.function() and ExpressionBuilder.operator(). Any given variables can be set on the Expression object returned by ExpressionBuilder.build() via calls to Expression.variable()
For evaluating expressions asynchronously the user only has to supply a java.util.concurrent.ExecutorService.
Evaluate a simple expression asynchronously
ExecutorService exec = Executors.newFixedThreadPool(1); Expression e = new ExpressionBuilder("3log(y)/(x+1)") .variables("x", "y") .build() .setVariable("x", 2.3) .setVariable("y", 3.14); Future<Double> future = e.evaluateAsync(exec); double result = future.get();
Variable names must start with a letter or the underscore _ and can only include letters, digits or underscores.
the following are valid variable names:
while 1_var_x is not as it does not start with a letter or a underscore.
Since v0.4.0 exp4j does support implicit multiplication. Therefore an expression like 2cos(yx) will be interpreted as 2*cos(y*x)
Since version 0.4.6 the following common constants have been added to exp4j and are bound automatically: pi, π the value of π as defined in Math.PI, e the value of Euler's number e, φ the value of the golden ratio (1.61803398874)
Since version 0.3.5 it is possible to use scientific notation for numbers see wikipedia. The number is split into a significand/mantissa y and exponent x of the form yEx which is evaluated as y * 10^x. Be aware that 'e/E' is no operator but part of a number and therefore an expression like 1.1e-(x*2) can not be evaluated. An example using the Fine-structure constant α=7.2973525698 * 10^−3:
you can extend the abstract class Function in order to use custom functions in expressions. you only have to implement the apply(double... args) method. In the following example a function for the logarithm to the base 2 is created and used in a following expression.
A custom function calculating the logarithm to an arbitrary base using the identity log(value, base) = ln(value)/ln(base)
Function logb = new Function("logb", 2) { @Override public double apply(double... args) { return Math.log(args[0]) / Math.log(args[1]); } }; double result = new ExpressionBuilder("logb(8, 2)") .function(logb) .build() .evaluate(); double expected = 3; assertEquals(expected, result, 0d);
you can also define multi argument functions like avg(a,b,c,d) via the constructor Function(String name, int argc), with argc being the argument count. The following example uses a custom function which returns the average of four values.
A custom average function taking 4 arguments:
Function avg = new Function("avg", 4) { @Override public double apply(double... args) { double sum = 0; for (double arg : args) { sum += arg; } return sum / args.length; } }; double result = new ExpressionBuilder("avg(1,2,3,4)") .function(avg) .build() .evaluate(); double expected = 2.5d; assertEquals(expected, result, 0d);
you can extend the abstract class Operator in order to declare custom operators for use in expressions, with the symbol being a String consisting of !,#,§,$,&,;,:,~,<,>,|,=.. Be aware that adding a Operator with a used symbol overwrites any existing operators including the builtin ones. So it's possible to overwrite e.g. the + operator. The constructor of an Operator takes up to 4 arguments:
Create a custom operator for calculating the factorial
Operator factorial = new Operator("!", 1, true, Operator.PRECEDENCE_POWER + 1) { @Override public double apply(double... args) { final int arg = (int) args[0]; if ((double) arg != args[0]) { throw new IllegalArgumentException("Operand for factorial has to be an integer"); } if (arg < 0) { throw new IllegalArgumentException("The operand of the factorial can not be less than zero"); } double result = 1; for (int i = 1; i <= arg; i++) { result *= i; } return result; } }; double result = new ExpressionBuilder("3!") .operator(factorial) .build() .evaluate(); double expected = 6d; assertEquals(expected, result, 0d);
Create a custom operator logical operator that returns 1 if the first argument is greater or equals than the second argument, and otherwise it returns 0.
@Test public void testOperators3() throws Exception { Operator gteq = new Operator(">=", 2, true, Operator.PRECEDENCE_ADDITION - 1) { @Override public double apply(double[] values) { if (values[0] >= values[1]) { return 1d; } else { return 0d; } } }; Expression e = new ExpressionBuilder("1>=2").operator(gteq) .build(); assertTrue(0d == e.evaluate()); e = new ExpressionBuilder("2>=1").operator(gteq) .build(); assertTrue(1d == e.evaluate());
The precedence of the unary minus operator is lower than the precedence of the power operator. This means that an expression like -1^2 is evaluated as -(1^2) not as (-1)^2.
exp4j throws a ArithmeticException when a division by zero is attempted. When implementing Operator or Function involving divisions the implementor has to make sure that a corresponding RuntimeException is thrown.
Throw an Arithmetic exception when a division by zero is attempted
Operator reciprocal = new Operator("$", 1, true, Operator.PRECEDENCE_DIVISION) { @Override public double apply(final double... args) { if (args[0] == 0d) { throw new ArithmeticException("Division by zero!"); } return 1d / args[0]; } }; Expression e = new ExpressionBuilder("0$").operator(reciprocal).build(); e.evaluate(); // <- this call will throw an ArithmeticException
Since version 0.4.0 exp4j has an added feature to validate expressions. Users can call Expression.validate() to perform a relatively fast validation. The validate method also accepts a boolean argument, indicating if a check for empty variables should be performed.
Thanks to Leo there is a Tag Library available at https://github.com/leogtzr/exp4j_tld. This enables users to use exp4j directly in JSP pages.
Please let me know if you're project uses exp4j and you want it listed here