### exp4j 0.2.x API changes

#### posted by fas on 2011-07-18 . Tagged as exp4j, java, programming, math, projects

ExpressionBuilder builder=new ExpressionBuilder("34*2"); Calculable calc=builder.build(); assertTrue(68d == calc.calculate());

If variables are used, the ExpressionBuilder has to be told at least how the variables are named, using one of the following methods, before calling build():

- - Implicit variables in an expression starting with "f(...)": new ExpressionBuilder("f(x,y) = y * x");
- - ExpressionBuilder.withVariable(String var,double value)
- - ExpressionBuilder.withVariables(Map<String,Double> variables)
- - ExpressionBuilder.withVariableNames(String ... variableNames)

Variable values can also be set after building an expression by calling

Calculable.setVariable(String var,double value):

double varX = 1.3d; double varY = 4.22d; Calculable calc = new ExpressionBuilder("7*x + 3*y - log(y/x*12)^y").withVariable("x", varX).withVariable("y", varY).build(); double result = calc.calculate(); assertTrue(result == 7 * varX + 3 * varY - Math.pow(Math.log(varY / varX * 12), varY)); varX = 1.79854d; varY = 9281.123d; calc.setVariable("x", varX); calc.setVariable("y", varY); result = calc.calculate(); assertTrue(result == 7 * varX + 3 * varY - Math.pow(Math.log(varY / varX * 12), varY));

if ExpressionBuilder.withVariableNames(String ... variableNames) is used the method Calculable.setVariable(String var,double val) has to be invoked at least once to actually set variable values, not just their names.

**de.congrace.exp4j.CustomFunction interface**

The CustomFunction interface has been added to give users the possibility to define their own functions to be used in expressions

So when someone wants to use half(x) as a function name which halfs any given number the CustomFunction interface can be used:

CustomFunction custom1 = new CustomFunction("half") { @Override public double applyFunction(double[] values) { return values[0] / 2d; } }; Calculable calc = new ExpressionBuilder("half(x)") .withVariable("x", 1d) .withCustomFunction(custom1) .build(); assertTrue(0.5d == calc.calculate());

Thanks go out to Folkert van Heusden who suggested having user defined functions in exp4j and who's request was key in motivating me to implement the ExpressionBuilder API.

Tags: exp4j, java, programming, math, projects