C hypot
hypot computes the Euclidean length of two components and avoids unnecessary overflow or underflow in the intermediate squares.
A simple example
hypot
- Start with Legs 3 and 4
- Do this Combine perpendicular lengths
- Result 5
#include <stdio.h>
#include <math.h>
int main(void) {
printf("%.15g\n", (double) (hypot(3.0, 4.0)));
}
5
Syntax
double hypot(double x, double y)
Run this example in C
Save the program as lesson.c. Use C17 and a Unix-style shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson
Measure a diagonal without squaring each side
A map records two perpendicular components of a journey. Compute the straight-line distance using a method that can also handle component sizes for which intermediate squaring would lose range.
#include <stdio.h>
#include <math.h>
int main(void) {
printf("%.1f\n", hypot(-3.0, 4.0));
printf("%d\n", isfinite(hypot(1e200, 1e200)) ? 1 : 0);
return 0;
}
5.0 1
A displacement of −3 horizontally and 4 vertically still has length 5. For two very large coordinates, squaring them directly can overflow even when the final length fits.
Open Group function reference for hypot
Estimate a direct walk across campus
A student crosses a courtyard instead of following two perpendicular paths around it. Calculate the direct walking distance from the horizontal and vertical distances shown on the campus map.
#include <math.h>
#include <stdio.h>
int main(void) {
double east = 6.0;
double north = 8.0;
printf("%.3f\n", hypot(east, north));
return 0;
}
10.000
Six blocks east and eight north form perpendicular sides. Their direct diagonal measures ten blocks.
Measure an exhibit’s diagonal cable route
An exhibition plan shows a socket 5 m east and 12 m north of a screen. A drafter marks the straight-line separation on the plan.
The perpendicular offsets form the legs of a right triangle.