Java - Math.sqrt() Method



Description

The java.lang.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.

Syntax

public static double sqrt(double d)

Parameters

Here is the detail of parameters −

  • d − Any primitive data type.

Return Value

  • This method returns the square root of the argument.

Example 1

In this example, we're showing the usage of Math.sqrt() method to get the square root of a double value. We've created a double variables d and initialized it with a value. Then using Math.sqrt() method we're printing the square root of the given double value.

public class Test { 
   public static void main(String args[]) {
      double x = 9.0;
      System.out.printf("sqrt(%.3f) is %.3f%n", x, Math.sqrt(x));
   }
}

This will produce the following result −

Output

sqrt(9.000) is 3.000

Example 2

In this example, we're showing the usage of Math.sqrt() method to get the square root of a float value. We've created a float variables d and initialized it with a value. Then using Math.sqrt() method we're printing the square root of the given float value.

public class Test { 
   public static void main(String args[]) {
      float x = (float)9.0;
      System.out.printf("sqrt(%.3f) is %.3f%n", x, Math.sqrt(x));
   }
}

This will produce the following result −

Output

sqrt(9.000) is 3.000

Example 3

In this example, we're showing the usage of Math.sqrt() method to get the square root of a zero value. We've created a double variables d and initialized it with a zero value. Then using Math.sqrt() method we're printing the square root of the given double value.

public class Test { 
   public static void main(String args[]) {
      double x = 0.0;
      System.out.printf("sqrt(%.3f) is %.3f%n", x, Math.sqrt(x));
   }
}

This will produce the following result −

Output

sqrt(0.000) is 0.000
java_numbers.htm
Advertisements