Open In App

Java Math hypot() Method

Last Updated : 07 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The Math.hypot() function is an in-built Math function in Java. Before going deep dive to the topic, first understand the reason behind to use this function.

Suppose we have a right-angled triangle and we know the lengths of the two shorter sides i.e., x and y. To calculate the hypotenuse, we use sqrt(x*x + y*y) formula. But Java has this in-built function i.e., Math.hypot() to handle very large or small values easily.

This function returns the Euclidean distance of a right-angled triangle with the sides of length x and y. The method returns sqrt(x2 + y2) without intermediate overflow or underflow.

 \sqrt{(x * x + y * y)}
  • If the argument is infinite, then the result is positive infinity.
  • If the argument is NaN and neither argument is infinite, then the result is NaN.

Syntax of Math hypot() Method

public static double hypot(double x, double y)

  • Parameter: x and y are the lengths of the sides.
  • Returns: It returns the square root of (x*x + y*y) without intermediate overflow or underflow. 

Examples of Java Math hypot() Method

Example 1: In this example, we will see the working of java.lang.Math.hypot() method.

Java
// Java program to demonstrate working 
// of java.lang.Math.hypot() method 
public class Geeks {
    
    public static void main(String[] args) {
        
        double x = 3.0;
        double y = 4.0;
        System.out.println("hypot(3,4): " + Math.hypot(x, y));
    }
}

Output
hypot(3,4): 5.0

Explanation: The square root of (3*3 + 4*4) is 5.


Example 2: In this example, we will see how to handle NaN.

Java
// Java program to handle NaN
public class Geeks {
    
    public static void main(String[] args) {
        
        double nan = Double.NaN;
        double y   = 2.0;
        System.out.println("hypot(NaN,2): " + Math.hypot(nan, y));
    }
}

Output
hypot(NaN,2): NaN

Explanation: Here, one argument is NaN and one is no infinite value, so the result id NaN.


Example 3: In this example, we will see how to handle infinite values.

Java
// Java program to handle infinite values
public class Geeks {
    
    public static void main(String[] args) {
        
        double p = Double.POSITIVE_INFINITY;
        double n = Double.NEGATIVE_INFINITY;
        System.out.println("hypot(Inf,5): " + Math.hypot(p, 5));
        System.out.println("hypot(Inf, -Inf): " + Math.hypot(p, n));
    }
}

Output
hypot(Inf,5): Infinity
hypot(Inf, -Inf): Infinity

Explanation: Here, both the arguments are infinite, so it results hypotenuse.


Next Article

Similar Reads