exp4j 0.3.5 API

Using the ExpressionBuilder and the Calculable interface

See:
          Description

Packages
de.congrace.exp4j  

 

Using the ExpressionBuilder and the Calculable interface

Evaluate an expression
                Calculable calc = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)").withVariable("x", varX).withVariable("y", varY).build()
                double result1=calc.calculate();
        
you can also change variables values after building by invoking Calculable.setVariable(String varName,double value), but one has to make sure that the variable names are passed into the ExpressionBuilder using at least ExpressionBuilder.withVariableNames(String...). If variables are used in the expression without setting at least their names, an UnparseableExpressionException will be thrown.
                Calculable calc = new ExpressionBuilder("x * y - 2").withVariableNames("x","y").build();
                calc.setVariable("x",1);
                calc.setVariable("x",2);
                assertTrue(calc.calculate()==0);
        
Using custom functions
you can extend the abstract class CustomFunction in order to use custom functions in expressions. You only have to implement the applyFunction(double value) method.
                CustomFunction fooFunc = new CustomFunction("foo") {
                        public double applyFunction(double value) {
                                return value*Math.E;
                        }
                };
                double varX=12d;
                Calculable calc = new ExpressionBuilder("foo(x)").withCustomFunction(fooFunc).withVariable("x",varX).build();
                assertTrue(calc.calculate() == Math.E * varX);
        
Using custom operators
you can extend the abstract class CustomOperator in order to use your own operators in expressions. You only have to implement the applyOperation(double value) method. CustomOperator's constructor takes four arguments:
       CustomOperator greaterEq = new CustomOperator(">=", true, 4, 2) {
            double applyOperation(double[] values) {
                if (values[0] >= values[1]){
                        return 1d;
                }else{
                        return 0d;
                }
            }
        };
        Calculable calc = new ExpressionBuilder("1>=2").withOperation(greaterEq).build();
        assertTrue(0d == calc.calculate());
        
Operators and functions

the following operators are supported: the following functions are supported:



Copyright © 2012. All Rights Reserved.