Q: I've noticed that JEP does not give accurate results for certain expressions. Why is this? What can I do about it?
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.
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.