A: You will notice that when you evaluate something as simple as "8 - 7.9" the result will be 0.09999999999999964 rather than 0.1. These inaccuracies are the result of floating point arithmetic. Internally, Jep uses the
double
type to represent numbers by default. Unfortunately, even for trivial calculations such as "8 - 7.9" the calculation can not be performed accurately.You will notice the same if you run the following code.
double a=8, b=7.9; System.out.println("a-b = " + (a-b)); //prints a-b = 0.09999999999999964So this is not a Jep flaw, just a limitation of using floating point numbers. Although floating point numbers are accurate enough for many applications, these types of errors should not be ignored in applications where accuracy is critical.
By using System.out.printf results from Jep can be displayed to a given number of decimal places. For example
jep.parse("8-7.9"); double res = jep.evaluateD(); System.out.printf("%.3f",res);Which will print the result to three decimal places: 0.100. See java.util.Formatter for details on formatting output. The java.text.NumberFormat class can also be used to format results.
Jep has a round function, which can round arguments to a given number of decimal places.
round(8-7.9,1)
will round results to one decimal place.To avoid this problem, use the BigDecimal components as described in the BigDecimal section. They allow you to perform calculations with arbitrary accuracy unlike floating point arithmetic.
A: By default variables who values have not been set by either
jep.addVariable(name,value);
or by parsing a expression like
XXX = 123.456;
will have a null value. By default the evaluator will throw an exception when null values are encountered.
There are a couple of ways round this:
((StandardEvaluator)jep.getEvaluator()).setTrapNullValues(false);
jep.getVariableFactory().setDefaultValue(Double.valueOf(0.0));