- Introduction
- Usage
- Evaluating an expression
- Evaluating an expression asynchronously
- Variable declaration
- Implicit multiplication
- Scientific notation
- Custom functions
- Custom operators
- Precedence of unary minus and power operators
- Division by zero in operations and functions
- Built-in functions
- Validation of expression
- Error handling

- Tag Library
- Links
- References

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:

`varX``_x1``_var_X_1`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.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:

- the symbol used for this operation (A String consisting of
`!,#,§,$,&,;,:,~,<,>,|,=`) - if the operation is left associative
- the precedence of the operation
- the number of operands the operator has (
`1 or 2`)

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()); Expression 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

`abs`: absolute value`acos`: arc cosine`asin`: arc sine`atan`: arc tangent`cbrt`: cubic root`ceil`: nearest upper integer`cos`: cosine`cosh`: hyperbolic cosine`exp`: euler's number raised to the power (e^x)`floor`: nearest lower integer`log`: logarithmus naturalis (base e)`log10`: logarithm (base 10)`log2`: logarithm (base 2)`sin`: sine`sinh`: hyperbolic sine`sqrt`: square root`tan`: tangent`tanh`: hyperbolic tangent

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.

- Version 0.4.3: Unicode names support added
- Version 0.4.1: Future API introduced
- Version 0.4.0: New Expression/ExpressionBuilder API
- Version 0.3.2: choice for unary minus precedence via System property
- Version 0.3.0: implicit variable declarations á la "f(x)=2x" have been removed
- Version 0.3.0: PostfixExpression API has been removed
- Version 0.3.0: The CustomOperator API has been added
- Version 0.2.5: the argument type for CustomFunction changed from double to double[] with an array holding the arguments of the function call, in order to allow multi argument functions like max(x,y,z)
- Version 0.2.2: the PostfixExpression API has been marked deprecated.
- Version 0.2.1: the CustomFunction API has been added
- Version 0.2.0: the ExpressionBuilder/Calculable API has been added

- exp4j intro for Version 0.3.x
- exp4j update 0.2.x
- Javier Llamas blogged about exp4j
- Catalin Alexandru blogged about exp4j
- Fernando Ribeiro blogged about exp4j
- Marek's php port of exp4j
- Leo's Tag Library for exp4j

- Nilgiri MUD uses exp4j
- JamWiki a java based wiki uses exp4j
- Catalin Alexandru blogged about exp4j
- JComplexity for algortihm comparison uses exp4j
- free{dom} building automation framework uses exp4j
- jHepWork a Multiplatform environment for scientific computation and data analysis uses exp4j
- cacl3d a 3d calculus visualisation engine uses exp4j.
Please let me know if you're project uses exp4j and you want it listed here