Java BigDecimal Power pow(BigDecimal arg0, BigDecimal arg1)

Here you can find the source of pow(BigDecimal arg0, BigDecimal arg1)

Description

pow

License

Mozilla Public License

Declaration

static BigDecimal pow(BigDecimal arg0, BigDecimal arg1) 

Method Source Code

//package com.java2s;
/** This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *///from ww  w  .  ja va  2 s .  c o m

import java.math.*;

public class Main {
    private static final MathContext MC_100 = new MathContext(100, RoundingMode.HALF_UP);

    static BigDecimal pow(BigDecimal arg0, BigDecimal arg1) {
        try {
            //check if arg1 (power) is an integer
            BigInteger bi = arg1.toBigIntegerExact();
            return arg0.pow(bi.intValue(), MC_100);
        } catch (ArithmeticException ex) {
            //arg1 is not an integer
            int n = arg1.intValue();
            switch (arg1.signum()) {
            case 0: //=0
                if (arg0.compareTo(BigDecimal.ZERO) != 0) {
                    return new BigDecimal(1);
                } else
                    throw new ArithmeticException("Invalid calculation: 0 ^ 0");

            case 1: //>0
            {
                BigDecimal result = arg0.pow(n);
                double x = Math.pow(arg0.doubleValue(), arg1.doubleValue() - n);
                if ((new Double(x).equals(Double.NaN))
                        || (new Double(Math.abs(x)).equals(Double.POSITIVE_INFINITY))) {
                    throw new ArithmeticException("too large result");
                } else {
                    return result.multiply(BigDecimal.valueOf(x));
                }
            }

            case -1: //<0
            {
                //n<0, so -n>0
                //e.g. 2.2^(-2.1)
                //now n=-2, result=(2.2^-2)*(2.2*-0.1)=(2.2*-0.1)/(2.2^2)
                BigDecimal result = arg0.pow(-n);
                double x = Math.pow(arg0.doubleValue(), arg1.doubleValue() - n);
                if ((new Double(x).equals(Double.NaN))
                        || (new Double(Math.abs(x)).equals(Double.POSITIVE_INFINITY))) {
                    throw new ArithmeticException("too large result");
                } else {
                    return BigDecimal.valueOf(x).divide(result, MC_100);
                }
            }

            default: //cannot happen
                throw new Error();
            }
        }
    }
}

Related

  1. decimalPow(BigDecimal number, BigDecimal power)
  2. pow(BigDecimal b, int p, int q)
  3. pow(BigDecimal base, BigDecimal exponent)
  4. pow(BigDecimal base, BigDecimal power)
  5. pow(BigDecimal one, int another)