What is Math.hypot in Java?

The hypot method is used to find the hypotenuse, sqrt(x2x^{2} + y2y^{2}), where x and y are of the double type.

hypot is a static method present in the Math class.

Syntax

double Math.hypot(double x, double y);

Return value

  • This method returns the hypotenuse: sqrt(x2x^{2} + y2y^{2}) of x and y.

  • If any one of the arguments is infinity, then Positive Infinity is returned.

  • If any of the arguments are NaN and both of the arguments are not infinite, then the result is NaN.

Example

class HelloWorld {
public static void main( String args[] ) {
double x = 8;
double y = 6;
System.out.println("Math.hypot(8,6) :" + Math.hypot(x,y));
x = Double.POSITIVE_INFINITY;
y = 6;
System.out.println("Math.hypot(Double.POSITIVE_INFINITY,6) :" + Math.hypot(x,y));
x = Math.sqrt(-2);
y = 6;
System.out.println("Math.hypot(sqrt(-2),6) :" + Math.hypot(x,y));
}
}

Explanation

  • In the first case, we find the hypotenuse of 8 and 6, which is equal to:

sqrt(828^{2} + 626^{2})

= sqrt(64 + 36)

= sqrt(100)

= 10

  • In the second case, we find the hypotenuse of Positive infinity and 6. If any one of the arguments is infinity, then Positive Infinity is returned.

  • In the third case, we assigned the value of x as Math.sqrt(-2), which is equal to NaN. So the value of x is NaN and y is 6. If any of the arguments are NaN and both of the arguments are not infinite, then the result is NaN.

Free Resources