hypot() Function
The hypot()
function computes the length of the hypotenuse of a right-angled triangle based on the lengths of its legs, following the Pythagorean theorem. It performs this computation in a way that minimizes the risk of overflow or underflow during intermediate calculations.
Syntax of hypot()
double hypot(double x, double y);
float hypotf(float x, float y);
long double hypotl(long double x, long double y);
Parameters
Parameter | Description |
---|---|
x | A floating point value representing one leg of a right-angled triangle. |
y | A floating point value representing the other leg of a right-angled triangle. |
The function computes the square root of the sum of the squares of its two arguments. It is designed to avoid unnecessary overflow or underflow during the calculation. In cases where the computed value exceeds the range of the return type, it may return HUGE_VAL
(or HUGE_VALF
/HUGE_VALL
) and set an overflow range error.
Examples for hypot()
Example 1: Calculating the Hypotenuse for a Standard Right Triangle
This example demonstrates the use of hypot()
to compute the hypotenuse of a right triangle with known leg lengths.
Program
#include <stdio.h>
#include <math.h>
int main() {
double a = 3.0, b = 4.0;
double result = hypot(a, b);
printf("Hypotenuse: %f\n", result);
return 0;
}
Explanation:
- The program initializes two double variables representing the legs of a right triangle.
- The
hypot()
function is called with these values to calculate the hypotenuse. - The resulting value, which should be 5.0, is printed to the console.
Program Output:
Hypotenuse: 5.000000
Example 2: Handling Very Large Values to Avoid Overflow
This example shows how hypot()
can safely compute the hypotenuse when provided with very large input values, thereby mitigating risks of overflow in intermediate calculations.
Program
#include <stdio.h>
#include <math.h>
int main() {
double a = 1e350, b = 1e300;
double result = hypot(a, b);
printf("Hypotenuse: %f\n", result);
return 0;
}
Explanation:
- The program initializes two very large double variables.
- The
hypot()
function is used to calculate the hypotenuse, which is the square root of the sum of their squares. - This approach avoids overflow during the computation by handling the large values internally.
- The result is printed, which may indicate an overflow scenario if the computed value exceeds the representable range.
Program Output:
main.c:5:5: warning: floating constant exceeds range of ‘double’ [-Woverflow]
5 | double a = 1e350, b = 1e300;
| ^~~~~~
Hypotenuse: inf