Java - Math sqrt(double x) method



Description

The Java Math sqrt(double a) returns the correctly rounded positive square root of a double value. Special cases −

  • If the argument is NaN or less than zero, then the result is NaN.

  • If the argument is positive infinity, then the result is positive infinity.

  • If the argument is positive zero or negative zero, then the result is the same as the argument.

Otherwise, the result is the double value closest to the true mathematical square root of the argument value.

Declaration

Following is the declaration for java.lang.Math.sqrt() method

public static double sqrt(double a)

Parameters

a − a value.

Return Value

This method returns the positive square root of a. If the argument is NaN or less than zero, the result is NaN.

Exception

NA

Example 1

The following example shows the usage of Math sqrt() method to get a square root of a positive double value.

package com.tutorialspoint;
public class MathDemo {
   public static void main(String[] args) {

      // get a double number
      double x = 1654.9874;

      // find the square root for this double number
      System.out.println("Math.sqrt(" + x + ")=" + Math.sqrt(x));
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Math.sqrt(1654.9874)=40.68153635250272

Example 2

The following example shows the usage of Math sqrt() method to get a value for a negative double value.

package com.tutorialspoint;
public class MathDemo {
   public static void main(String[] args) {

      // get a double number
      double x = -9765.134;

      // find the square root for this double number
      System.out.println("Math.sqrt(" + x + ")=" + Math.sqrt(x));
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Math.sqrt(-9765.134)=NaN

Example 3

The following example shows the usage of Math sqrt() method to get a value for a zero double values.

package com.tutorialspoint;
public class MathDemo {
   public static void main(String[] args) {

      // get double number
      double x = 0.0;	  

      // find the square root for this double number
      System.out.println("Math.sqrt(" + x + ")=" + Math.sqrt(x));
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Math.sqrt(0.0)=0.0
java_lang_math.htm
Advertisements