Java BigDecimal Power pow(BigDecimal base, BigDecimal exponent)

Here you can find the source of pow(BigDecimal base, BigDecimal exponent)

Description

pow

License

LGPL

Declaration

public static BigDecimal pow(BigDecimal base, BigDecimal exponent) 

Method Source Code


//package com.java2s;
//License from project: LGPL 

import java.math.BigDecimal;
import java.math.RoundingMode;

public class Main {
    public static BigDecimal pow(BigDecimal base, BigDecimal exponent) {
        BigDecimal result = BigDecimal.ZERO;
        int signOf2 = exponent.signum();

        // Perform X^(A+B)=X^A*X^B (B = remainder)
        double dn1 = base.doubleValue();
        // Compare the same row of digits according to context
        BigDecimal n2 = exponent.multiply(new BigDecimal(signOf2)); // n2 is now positive
        BigDecimal remainderOf2 = n2.remainder(BigDecimal.ONE);
        BigDecimal n2IntPart = n2.subtract(remainderOf2);
        // Calculate big part of the power using context -
        // bigger range and performance but lower accuracy
        BigDecimal intPow = base.pow(n2IntPart.intValueExact());
        BigDecimal doublePow = new BigDecimal(Math.pow(dn1, remainderOf2.doubleValue()));
        result = intPow.multiply(doublePow);

        // Fix negative power
        if (signOf2 == -1)
            result = BigDecimal.ONE.divide(result, RoundingMode.HALF_UP);
        return result;
    }/*from   w  w w  .  j a  va2 s.c  o m*/
}

Related

  1. decimalPow(BigDecimal number, BigDecimal power)
  2. pow(BigDecimal arg0, BigDecimal arg1)
  3. pow(BigDecimal b, int p, int q)
  4. pow(BigDecimal base, BigDecimal power)
  5. pow(BigDecimal one, int another)
  6. pow(BigDecimal savedValue, BigDecimal value)
  7. power(BigDecimal base, int exponent)