# BigDecimal pow function

• 07-02-2013, 10:03 AM
lipkerson
BigDecimal pow function
Hi

I'am looking for a method that operate on BigDecimals. I nedd to do x^y where x and y are BigDecimals.
I found a commercial library SuanShu but I prefer free solution.

There is

but exponent must be from range and with decimal part = 0. Otherwise it throws AritmeticException.

with regards
• 07-02-2013, 12:10 PM
JosAH
Re: BigDecimal pow function
Suppose you want to calculate a^b where both a and b are BigDecimals; suppose b has n fractional digits, so 10^n*b is an int or BigInteger.

So, a^b == a^(10^n*b)/a^(10^n); this reduces the problem to taking the power of a raised to a BigInteger or an int (twice); raising a^x where x is a BigInteger can be reduced to:

a^x == a^(x/2)*a^(x/2)*x iff x is odd;
a^x == a^(x/2)*a^(x/2) iff x is even;
a^x == a iff x is 1;
a^x == 1 iff x is 0
a^x can be calculated with BigDecimal.pow( ... ) iff x <= Integer.MAX_VALUE.

kind regards,

Jos
• 07-04-2013, 05:41 AM
jim829
Re: BigDecimal pow function
Quote:

Originally Posted by JosAH
Suppose you want to calculate a^b where both a and b are BigDecimals; suppose b has n fractional digits, so 10^n*b is an int or BigInteger.

So, a^b == a^(10^n*b)/a^(10^n)

I don't believe this is true. Let a = 2.0, b = 1.2. Then n = 1
(a^12)/(a^10) = a^2 = 4. But 2^1.2 is approx 2.297.

Regards,
Jim
• 07-04-2013, 09:51 AM
JosAH
Re: BigDecimal pow function
Quote:

Originally Posted by jim829
I don't believe this is true. Let a = 2.0, b = 1.2. Then n = 1
(a^12)/(a^10) = a^2 = 4. But 2^1.2 is approx 2.297.

Of course it isn't true; some moron must've doodled it down while he was still asleep (he probably hadn't had his espresso yet); the last part of all that nonsense is true but trivial; I didn't have my esprsso yet either; I'll probably get back to this later. Maybe a bit of fiddling with the BigDecimal.setScale( ... ) method can do the trick ...

kind regards,

Jos
• 07-04-2013, 01:50 PM
jim829
Re: BigDecimal pow function
Well, I've worked on this some but I can't seem to figure it out. Somewhere, somehow I keep getting stuck with having to take the 10^n root of the result. This is because a^(10^n*b) == (a^b)^10^n. In any event, I usually end up with some decimal as part of the exponent so I am back to square one.

Regards,
Jim

P.S. Savor the Espresso.
• 07-04-2013, 04:30 PM
JosAH
Re: BigDecimal pow function
Quote:

Originally Posted by jim829
Well, I've worked on this some but I can't seem to figure it out. Somewhere, somehow I keep getting stuck with having to take the 10^n root of the result. This is because a^(10^n*b) == (a^b)^10^n. In any event, I usually end up with some decimal as part of the exponent so I am back to square one.

Regards,
Jim

P.S. Savor the Espresso.

I have no results either; I think you have to go the log/exp way, i.e. a^b= exp(log(a^b)) == exp(b*log(a)) and hopefully some of the calculations can be cut out ...

kind regards,

Jos