With Jep.Net 3, it is now possible to evaluate expressions using decimal arithmetic. This allows calculations to be performed with specified accuracy or even unlimited accuracy. If you are running into precision problems or already know that you will require the highest possible precision in your calculations, we recommend using this operation mode.
Rather than using the double
type to represent numbers, BigDecimal
is used. The BigDecimal
class is part of the Java API and is
contained in the java.math
package. For more information on this
class, please read the Sun
Javadocs for BigDecimal.
The difference in the accuracy is best shown through an example. When performing
multiplication of two numbers of the double
type,
10*0.09 evaluates as 0.8999999999999999.
But when performing the same calculation using decimal arithmetic with the
BigDecimal
type,
10*0.09 evaluates as 0.9.
Using Jep.Net in BigDecimal mode is simple. Simply create a new Jep.Net instance with:
import com.singularsys.jep.bigDecimals.BigDecComponents; ... jep = new Jep(new BigDecComponents());
This initializes Jep.Net with a special the BigDecNumberFactory, BigDecOperatorTable and BigDecFunctionTable. By default the math context is set to unlimited precision. But you can also initialize the components with a different math context. For example, to use 32-bit precision numbers simply use
jep = new Jep(new BigDecComponents(MathContext.DECIMAL32));
For more information about MathContexts, refer to the Sun MathContext Javadocs.
Guaranteeing precision unfortunately comes at the cost of more complex algorithms
for basic operators and functions. For this reason, some of the functions
and operators available for double
arithmetic are not available
in the BigDecimal mode.
The supported operators and functions are as follows:
+, -, *, /, ^ (power), % (modulus)
>, <, >=, <=, == (equals)
&& (and), || (or), ! (not)
Just like with Jep.Net in standard mode, you can add your own custom functions.