Java Math hypot() Method
The hypot() method of Math class returns the square root for the expression x2 + y2 without the intermediate underflow or overflow .
Syntax:
public static double hypot(double x, double y)
Parameters:
The parameters ‘x’ and ‘y’ represent the values.
Return Value:
The hypot () method returns the square root for the expression x2 + y2.
Special cases of the hypot() method are as follows:
- It returns positive infinity, if either argument is infinite.
- It returns NaN , if either argument is NaN and neither argument is infinite.
Example 1:
public class JavaMathHypotExample1 { public static void main(String[] args) { double a = 4; double b = 3; //returns the square root for the expression x.x + y.y System.out.println("Hypotenuse : "+Math.hypot(a,b)); } }
Output:
Hypotenuse : 5.0
Example 2:
public class JavaMathHypotExample2 { public static void main(String[] args) { double a = 12; double b = 5; double c=Math.hypot(a, b); //returns the square root for the expression x.x + y.y System.out.println("Hypotenuse : " + c); double d=a*a+b*b; if(d==c*c){ System.out.println("The triangle ia a right angled triangle. "); } else{ System.out.println("The triangle is not a right angled triangle."); } } }
Output:
Hypotenuse : 13.0 The triangle ia a right angled triangle.
Example 3:
public class JavaMathHypotExample3 { public static void main(String[] args) { double a = 4/0.0d; double b = 3; //returns positive infinity, if either argument is infinite System.out.println("Hypotenuse : "+Math.hypot(a,b)); } }
Output:
Hypotenuse : Infinity
Example 4:
public class JavaMathHypotExample4 { public static void main(String[] args) { double a = -4/0.0d; double b = 3; //returns positive infinity, if either argument is negative infinite System.out.println("Hypotenuse : "+Math.hypot(a,b)); } }
Output:
Hypotenuse : Infinity
Example 5:
public class JavaMathHypotExample5 { public static void main(String[] args) { double a = 0.0d/0.0d; double b = 3; //returns NaN, if either argument is NaN System.out.println("Hypotenuse : "+Math.hypot(a,b)); } }
Output:
Hypotenuse : NaN