In Java, Math.hypot(x, y) returns the length of the hypotenuse of a right triangle with sides x and y, which is sqrt(x * x + y * y). Math.hypot(3, 4) is 5.0.
It is mainly used for the distance between two points and the length of a 2D vector. Unlike the hand-written formula, it avoids a temporary overflow or underflow in the squares. It was added in Java 5 (JDK 1.5).
A static method of the java.lang.Math class, added in Java 5 (JDK 1.5). Call it on the class name, as in Math.hypot(...). No import is needed, because classes in java.lang are always visible.
Syntax
Pass the two side lengths; the signs do not matter. The result is a double.
hypot takes exactly two arguments. For three or more dimensions, nest the calls. The result is within one unit in the last place of the true value, and it is a bit slower than a plain sqrt, so use Math.sqrt(x * x + y * y) in tight loops where overflow cannot happen.
The square root of x*x + y*y, computed so that the squares cannot overflow or underflow. If either argument is infinite, the result is Infinity, even when the other one is NaN; otherwise a NaN argument gives NaN.
The square is the culprit. The true value 1e400 is far above the largest double (about 1.8e308), so big * big becomes Infinity and drags the whole formula with it.
Scaled inside.hypot rescales its arguments internally, so the answer is finite; dividing by 1e200 shows the factor 1.4142, the square root of 2.
Underflow is the mirror image. 1e-200 squared is 1e-400, below the smallest positive double, so it becomes 0.0 and the naive length is 0.0, while hypot stays above zero.
Example 3 — Negative Sides, Zero, Infinity, and NaN
The unusual inputs and what hypot returns for them.
Lengths are never negative. The sides are squared, so -3 and -4 behave like 3 and 4 and the result is the positive 5.0.
Zero sides. A triangle with both sides 0 has hypotenuse 0.0, always a positive zero.
An infinite side wins. If one side is already infinite, the length is infinite no matter what the other value is, so Infinity beats NaN; a lone NaN with a finite side stays NaN.
Frequently Asked Questions
It returns the square root of x squared plus y squared, which is the length of the hypotenuse of a right triangle. Math.hypot(3, 4) returns 5.0.
They agree for normal values. hypot avoids intermediate overflow and underflow, so it still works with very large or very small numbers, where the plain formula gives Infinity or 0.0.
Call Math.hypot(x2 - x1, y2 - y1). For 3D points, nest the calls: Math.hypot(Math.hypot(dx, dy), dz).
Yes. The signs do not matter because the values are squared: Math.hypot(-3, -4) is 5.0.
Java 5 (JDK 1.5). Older versions need Math.sqrt(x * x + y * y).