Calculates a^b - Java java.lang

Java examples for java.lang:Math Calculation

Description

Calculates a^b

Demo Code

/*/*  www . jav  a 2 s  . c  o m*/
 * Created on 02-May-2006 at 17:31:01.
 * 
 * Copyright (c) 2010 Robert Virkus / Enough Software
 *
 * This file is part of J2ME Polish.
 *
 * J2ME Polish 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.
 * 
 * J2ME Polish 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 J2ME Polish; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 * Commercial licenses are also available, please
 * refer to the accompanying LICENSE.txt or visit
 * http://www.j2mepolish.org for details.
 */
//package com.java2s;

public class Main {
    /**
     * Calculates a^b
     * @param a a
     * @param b b
     * @return a^b
     */
    public static double pow(double a, double b) {
        if (b == 0) {
            return 1;
        }
        boolean gt1 = (Math.sqrt((a - 1) * (a - 1)) <= 1) ? false : true;
        int oc = -1, iter = 30;
        double p = a, x, x2, sumX, sumY;

        if ((b - Math.floor(b)) == 0) {
            for (int i = 1; i < b; i++)
                p *= a;
            return p;
        }

        x = (gt1) ? (a / (a - 1)) : (a - 1);
        sumX = (gt1) ? (1 / x) : x;

        for (int i = 2; i < iter; i++) {
            p = x;
            for (int j = 1; j < i; j++)
                p *= x;

            double xTemp = (gt1) ? (1 / (i * p)) : (p / i);

            sumX = (gt1) ? (sumX + xTemp) : (sumX + (xTemp * oc));

            oc *= -1;
        }

        x2 = b * sumX;
        sumY = 1 + x2;

        for (int i = 2; i <= iter; i++) {
            p = x2;
            for (int j = 1; j < i; j++)
                p *= x2;

            int yTemp = 2;
            for (int j = i; j > 2; j--)
                yTemp *= j;

            sumY += p / yTemp;
        }

        return sumY;
    }
}

Related Tutorials