BigDecimal Rounding using power operator

3 views
Skip to first unread message

Joe Stiefel

unread,
Jul 9, 2021, 8:02:35 PMJul 9
to Jep Java Users

Hi
I am evaluating this tool for an application I am writing. I require accurate representation that BigDecimal provides. I am running into a "java.lang.ArithmeticException: Rounding necessary" exception when trying to use the Power operator for some calculations, even though I passed in a "MathContext.DECIMAL64"(I believe this denotes "Half up" rounding to 16 places) to the BigDecComponents() constructor. Here is my code:

        Jep jep = new Jep( new BigDecComponents(MathContext.DECIMAL64));
        String math = ".1 ^ .2";
        jep.parse(math);
        Object evaluate = jep.evaluate();

I am aware that I can write my own power operator function, I am just curious why this tool does not use the rounding method associated with MathContext.DECIMAL64 or even any specified rounding passed in using other Mathcontext constructors.

Thanks

Joe


Richard Morris

unread,
Jul 10, 2021, 3:12:32 AMJul 10
to Jep Java Users
The problem here is in the java.math.BigDecimal class is really quite limited and only supports raising to integer powers

There are two methods

BigDecimal

pow(int n)
Returns a BigDecimal whose value is (this^n), The power is computed exactly, to unlimited precision.

BigDecimal

pow(int n, MathContext mc)
Returns a BigDecimal whose value is (this^n).

So there is no straightforward way to implement non-integer powers for big decimal.

There are some third party libraries that do provide implementations. See

As a general rule I would advise most people against using big decimals. There are a lot of pitfalls in using the library which is more geared towards financial calculations, there are better ways to  implement high precision see suggestions at


In the core Jep we want to not have dependencies on third party libraries. In the extensions package there is a Field framework that makes it easier to include third party libraries.
Reply all
Reply to author
Forward
0 new messages