Math.sqrt()
Returns the square root of a number.
Available since: Java 1.0
Syntax
static double sqrt(double a)Parameters
| Parameter | Type | Description |
|---|---|---|
| a | double | A non-negative number. |
Return value
doubleThe root as a double; NaN for a negative number.
Examples
A root and the hypotenuse of a triangle:
void main() {
IO.println(Math.sqrt(16));
IO.println(Math.sqrt(2));
IO.println(Math.sqrt(3 * 3 + 4 * 4));
IO.println(Math.sqrt(-1));
}Output:
4.0
1.4142135623730951
5.0
NaNNotes
There is no exception for negative numbers — the result is NaN ("not a number"). Check it with Double.isNaN(x); the comparison x == Double.NaN is always false. The cube root is Math.cbrt(), the hypotenuse Math.hypot(a, b).
See also
- Math.pow() — Raises a number to a power.
- Math.abs() — Returns the absolute value of a number — the value without a minus sign.
Related recipes
In the tutorial
- Operators — Java arithmetic operators, integer division and remainder, compound assignment, increment, comparison and logical operators.