EN
Java - Math.sqrt() method example
0
points
Math
sqrt
is a static method that returns a number which is the square root of input value. The method works only on positive real numbers.
public class MathExample {
public static void main(String[] args) {
System.out.println( Math.sqrt( 4 ) ); // 2.0
System.out.println( Math.sqrt( 9 ) ); // 3.0
System.out.println( Math.sqrt( 2 ) ); // 1.4142135623730951
System.out.println( Math.sqrt( 0.5 ) ); // 0.7071067811865476
System.out.println( Math.sqrt( 0 ) ); // 0.0
System.out.println( Math.sqrt( -1 ) ); // NaN
}
}
1. Documentation
Syntax |
|
Parameters | number - double value in the range 0 to +Infinity (primitive value). |
Result |
Square root If the operation can not be executed |
Description | sqrt is a static method that returns a number which is square root of input value. The method works only on positive real numbers. |
2. Square root with Math.pow
method examples
In this example, the way how to calculate square root using power function is presented.
public class MathExample {
static double calculateSqrt(double value) {
return Math.pow(value, 0.5);
}
public static void main(String[] args) {
// Examples:
System.out.println( calculateSqrt( 4 ) ); // 2
System.out.println( calculateSqrt( 9 ) ); // 3
System.out.println( calculateSqrt( 2 ) ); // 1.4142135623730951
System.out.println( calculateSqrt( 0.5 ) ); // 0.7071067811865476
System.out.println( calculateSqrt( 0 ) ); // 0
System.out.println( calculateSqrt( -1 ) ); // NaN
}
}