Selected Reading

C++ cmath hypot() Function



The C++ cmath hypot() function is used to calculate the length of the hypotenuse of a right-angled triangle, using the Pythagorean theorem. This function takes two side lengths as arguments and returns the square root of the sum of their squares.

This function provides accurate calculations by avoiding overflow and underflow issues, which occurs when manually squaring and calculating the large or small floating-point numbers.

Syntax

Following is the syntax for C++ cmath hypot() function.

double hypot(double x, double y);
or
float hypot(float x, float y);
or
long double hypot(long double x, long double y);

Parameters

  • x - The length of one side of the right-angled triangle.

  • y - The length of another side of the right-angled triangle.

Return Value

The function returns the square root of (x2+y2)

Time Complexity

The time complexity of this function is constant, i.e.,O(1).

Example 1

The following example shows the basic usage of hypot(), by calculating hypotenuse length for a triangle with perpendicular sides

#include <iostream>
#include <cmath>
int main() {
   double x = 3.0, y = 4.0;
   double result = std::hypot(x, y);
   std::cout << "Hypotenuse for sides 3 and 4 is: " << result << std::endl;
   return 0;
}

Output

Output of the above code is as follows

Hypotenuse for sides 3 and 4 is: 5

Example 2

In this example, we are going to calculate the hypotenuse for sides having negative values.

#include <iostream>
#include <cmath>
int main() {
   double x = -7.0, y = 24.0;
   double result = std::hypot(x, y);
   std::cout << "Hypotenuse for sides -7.0 and 24.0 is: " << result << std::endl;
   return 0;
}

Output

Following is the output of the above code

Hypotenuse for sides -7.0 and 24.0 is: 25

Example 3

Let's calculate the distance between two points using hypot(), which computes the straight-line distance in 2D space.

#include <iostream>
#include <cmath>
int main() {
   double x1 = 1.0, y1 = 2.0;
   double x2 = 4.0, y2 = 6.0;
   double distance = hypot(x2 - x1, y2 - y1);
   std::cout << "The distance between points (" << x1 << ", " << y1 << ") and (" << x2 << ", " << y2 << ") is " << distance << std::endl;
   return 0;
}

Output

If we run the above code it will generate the following output

The distance between points (1, 2) and (4, 6) is 5
cpp_cmath.htm
Advertisements