Math.pow in Java

Updated on December 23rd, 2018

Math.pow in Java

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

 

1.  Math.pow Example

Math.pow have a 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 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. It does not require us 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.

 

2.  Xor and Pow

Xor and Pow are different and they can create confusion. When we write ab , we follow below syntax

Mathematics
2^3 = 2x2x2 = 8

// Using Math.pow
Math.pow(2, 3)

In Java, ^ is known as xor operator which differs from the power operation. Let’s look at the following example for more details.

package com.javadevjournal;

import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class MathPowXorTest {

 private static final double DELTA = 0.001 d;

 @Test
 public void xorOperatorTest() {
  assertEquals(8 d, Math.pow(2 d, 3 d), DELTA);
  assertEquals(7 d, 2 ^ 5, DELTA);
 }
}

 

Summary

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

Java Development Journal

Hello!! Welcome to the Java Development Journal. We love to share our knowledge with our readers and love to build a thriving community.

follow me on:

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of