Arthur Julião
Arthur Julião

Reputation: 869

How to calculate power with no integer bigdecimal expoent?

Trying to calculate (a+b)^n where n is a real value in a BigDecimal variable, but BigDecimal.pow is designed for accept only integer values.

Upvotes: 3

Views: 1689

Answers (2)

Sabumnim
Sabumnim

Reputation: 711

As long as you are just using an integer for the exponent, you can use a simple loop to calculate x^y:

public static BigDecimal pow(BigDecimal x, BigInteger y) {
    if(y.compareTo(BigInteger.ZERO)==0) return BigDecimal.valueOf(1); //If the exponent is 0 then return 1 because x^0=1
    BigDecimal out = x;
    BigInteger i = BigInteger.valueOf(1);
    while(i.compareTo(y.abs())<0) {                                   //for(BigDecimal i = 1; i<y.abs(); i++) but in BigDecimal form
        out = out.multiply(x);
        i = i.add(BigInteger.ONE);
    }
    if(y.compareTo(BigInteger.ZERO)>0) {
        return out;
    } else if(y.compareTo(BigInteger.ZERO))<0) {
        return BigDecimal.ONE.divide(out, MathContext.DECIMAL128);    //Just so that it doesn't throw an error of non-terminating decimal expansion (ie. 1.333333333...)
    } else return null;                                               //In case something goes wrong
}

or for a BigDecimal x and y:

public static BigDecimal powD(BigDecimal x, BigDecimal y) {
    return pow(x, y.toBigInteger());
}

Hope this helps!

Upvotes: 0

Patricia Shanahan
Patricia Shanahan

Reputation: 26175

If the input is within the magnitude range supported by double, and you do not need more than 15 significant digits in the result, convert (a+b) and n to double, use Math.pow, and convert the result back to BigDecimal.

Upvotes: 0

Related Questions