Compute x^exponent to a given scale. - Java java.lang

Java examples for java.lang:Math Operation

Description

Compute x^exponent to a given scale.

Demo Code

/*/*from   ww w  . ja  v a 2  s  .c  o  m*/
 Anders H?fft, note: This class was downloaded as a quick, and temprory, way of getting a BigDecimal ln() method. 
 The code belongs to Cyclos. See comment below:

 This file is part of Cyclos (www.cyclos.org).
 A project of the Social Trade Organisation (www.socialtrade.org).
 Cyclos is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.
 Cyclos is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 GNU General Public License for more details.
 You should have received a copy of the GNU General Public License
 along with Cyclos; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
//package com.java2s;
import java.math.BigDecimal;

public class Main {
    public static void main(String[] argv) throws Exception {
        BigDecimal x = new BigDecimal("1234");
        long exponent = 2;
        int scale = 2;
        System.out.println(intPower(x, exponent, scale));
    }

    /**
     * Compute x^exponent to a given scale.
     * @param x the value x
     * @param exponent the exponent value
     * @param scale the desired scale of the result
     * @return the result value
     */
    public static BigDecimal intPower(BigDecimal x, long exponent,
            final int scale) {
        // If the exponent is negative, compute 1/(x^-exponent).
        if (exponent < 0) {
            return BigDecimal.valueOf(1).divide(
                    intPower(x, -exponent, scale), scale,
                    BigDecimal.ROUND_HALF_EVEN);
        }

        BigDecimal power = BigDecimal.valueOf(1);

        // Loop to compute value^exponent.
        while (exponent > 0) {

            // Is the rightmost bit a 1?
            if ((exponent & 1) == 1) {
                power = power.multiply(x).setScale(scale,
                        BigDecimal.ROUND_HALF_EVEN);
            }

            // Square x and shift exponent 1 bit to the right.
            x = x.multiply(x).setScale(scale, BigDecimal.ROUND_HALF_EVEN);
            exponent >>= 1;

            Thread.yield();
        }

        return power;
    }
}

Related Tutorials