Java sqrt() method with Examples
The java.lang.Math.sqrt() returns the square root of a value of type double passed to it as argument. If the argument is NaN or negative, then the result is NaN. If the argument is positive infinity, then the result is positive infinity. If the argument passed is positive zero or negative zero then the result will be same as that of the argument.
Syntax:
public static double sqrt(double a)
Parameter :
a : the value whose square root is to be returned.
Return :
This method returns the positive square root value of
the argument passed to it.
Example 1: To show working of java.lang.Math.sqrt() method.
import java.lang.Math;
class Gfg {
public static void main(String args[])
{
double a = 30 ;
System.out.println(Math.sqrt(a));
a = 45 ;
System.out.println(Math.sqrt(a));
a = 60 ;
System.out.println(Math.sqrt(a));
a = 90 ;
System.out.println(Math.sqrt(a));
}
}
|
Output:
5.477225575051661
6.708203932499369
7.745966692414834
9.486832980505138
Example 2: To show working of java.lang.Math.sqrt() method when argument is NaN or +infinity.
import java.lang.Math;
public class GFG {
public static void main(String[] args)
{
double positiveInfinity = Double.POSITIVE_INFINITY;
double negativeVal = - 5 ;
double nan = Double.NaN;
double result;
result = Math.sqrt(negativeVal);
System.out.println(result);
result = Math.sqrt(positiveInfinity);
System.out.println(result);
result = Math.sqrt(nan);
System.out.println(result);
}
}
|
Output:
NaN
Infinity
NaN
Last Updated :
09 Apr, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...