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.
xxxxxxxxxx
1
public class MathExample {
2
3
public static void main(String[] args) {
4
System.out.println( Math.sqrt( 4 ) ); // 2.0
5
System.out.println( Math.sqrt( 9 ) ); // 3.0
6
7
System.out.println( Math.sqrt( 2 ) ); // 1.4142135623730951
8
System.out.println( Math.sqrt( 0.5 ) ); // 0.7071067811865476
9
System.out.println( Math.sqrt( 0 ) ); // 0.0
10
System.out.println( Math.sqrt( -1 ) ); // NaN
11
}
12
}
Syntax |
xxxxxxxxxx 1 package java.lang; 2 3 public final class Math { 4 5 public static double sqrt(double number) { ... } 6 7 }
|
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. |
In this example, the way how to calculate square root using power function is presented.
xxxxxxxxxx
1
public class MathExample {
2
3
static double calculateSqrt(double value) {
4
return Math.pow(value, 0.5);
5
}
6
7
public static void main(String[] args) {
8
// Examples:
9
System.out.println( calculateSqrt( 4 ) ); // 2
10
System.out.println( calculateSqrt( 9 ) ); // 3
11
12
System.out.println( calculateSqrt( 2 ) ); // 1.4142135623730951
13
System.out.println( calculateSqrt( 0.5 ) ); // 0.7071067811865476
14
System.out.println( calculateSqrt( 0 ) ); // 0
15
System.out.println( calculateSqrt( -1 ) ); // NaN
16
}
17
}