Unfortunately you don’t have a solution ready. If converting to another type is a valid option, then you have no reason to use BigDecimal
. The conversion will cause loss of value, and worse, so that often naive tests will not detect.
Since Java does not provide anything ready you have to do a function of your own. There’s one in the O.R.:
public static BigDecimal powerBig(BigDecimal base, BigDecimal exponent) {
BigDecimal ans = new BigDecimal(1.0);
BigDecimal k = new BigDecimal(1.0);
BigDecimal t = new BigDecimal(-1.0);
BigDecimal no = new BigDecimal(0.0);
if (exponent != no) {
BigDecimal absExponent = exponent.signum() > 0 ? exponent : t.multiply(exponent);
while (absExponent.signum() > 0){
ans =ans.multiply(base);
absExponent = absExponent.subtract(BigDecimal.ONE);
}
if (exponent.signum() < 0) {
// For negative exponent, must invert
ans = k.divide(ans);
}
} else {
// exponent is 0
ans = k;
}
return ans;
}
I put in the Github for future reference.
Also has square root option.
Have libraries ready:
Avoid using
Math.pow
to work withBigDecimal
. You lose the desired properties– Jefferson Quesado
How would I make the calculation in question with Bigdecimal values?
– Weriky Alphazero
a mathematical bullshit involving logarithms and exponentials, I’m remembering here how
– Jefferson Quesado
Or use an external library: https://github.com/eobermuhlner/big-math
– Jefferson Quesado
I’m trying to remember the API of
BigDecimal
to view available operations– Jefferson Quesado
Well, I used a library to do the calculations of logarithms and exponentials, so I’m going to owe =\
– Jefferson Quesado