Skip navigation links

exp4j 0.4.8 API

Using the ExpressionBuilder and the Expression API

See: Description

Packages 
Package Description
net.objecthunter.exp4j  
net.objecthunter.exp4j.function  
net.objecthunter.exp4j.operator  
net.objecthunter.exp4j.shuntingyard  
net.objecthunter.exp4j.tokenizer  

Using the ExpressionBuilder and the Expression API

Evaluate an expression
        Expression e = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
                .variables("x", "y")
                .build()
                .setVariable("x", 2.3)
                .setVariable("y", 3.14);
        double result = e.evaluate();
    
Using custom functions

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. The following example shows the implementation of a function that calculates the logarithm to an arbitrary base using the identity logb(x) = ln(x)/ln(b)

        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);
        
Using custom operators

you can extend the abstract class Operator in order to use your own operators in expressions. You only have to implement the apply(double ... value) method. The Operator's constructor takes four arguments:

    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);
        
Operators and functions

the following operators are supported:

the following functions are supported:



Skip navigation links

Copyright © 2017. All Rights Reserved.