Math.pow in Java

Using Math.pow in Java

In this quick post, we will get an understanding of Using Math.pow in Java. power of the number in a very simple term indicates as to how many times to use a number for multiplication.

 

1.  Example

Math.pow have a very simple signature like

public static double pow(double a, double b), where 'a' indicates the base,  'b' indicated the exponent and Math.pow() will return the value as 

ab

Let’s look into a very simple example to understand how Mah.pow works.

@Test
public void calculateIntPow(){
    int a= 3;
    int b=4;

    int result = (int) Math.pow(a,b);

    assertEquals(81, result);
}

Since we were expecting results in an int, it was required to cast the output to int to get desired results.We are not required to cast results in case desired output is in double (which is also output for  of the Math.pow() method)

@Test
public void calculateDoublePow(){
    double a= 3.4;
    int b=4;

    double result =  Math.pow(a,b);

    assertEquals(133.63, result, 2);
}

There are certain features/properties of this method, read  Math.pow for more detail.

Summary

In this quick post, we get an understanding as to how to Use Math.pow method in Java to calculate the power of any given base.

JavaDevJournal

Hello!! I am Umesh- an engineer by profession and a photographer by passion.I like to build stuff on the web using OSS and love to capture the world through my lens.

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz