Search code examples
javaloopsmathpow

Making a copy of the Math.pow() method


I'm making a method that's supposed to do the same as Math.pow(), but I just can't figure out how to make it possible to use double values for y and get a double value result with decimals.... Any ideas (preferably using a for-loop)? In the method below I used "x" as the base and "y" as the exponent.

public static double power(double x, double y) {
    double result = 1;
    if (y <= 0)
        return 0;
    for (int count = 0; count < (int)y; count++)
        result *= x;
    return result;
}

Solution

  • You could use Math.log and Math.exp to acheive this.

    public static void main(String[] args) throws InterruptedException {
    
    
             System.out.println(power(2,2.5));
    
        }
    
    
      public static double power(double x, double y) {
    
        double val = y *  Math.log(x);
    
        double result = Math.exp(val);
    
                return result;
        }
    

    output is

    5.65685424949238