Library contents

C hypot

hypot computes the Euclidean length of two components and avoids unnecessary overflow or underflow in the intermediate squares.

A simple example

hypot

  1. Start with Legs 3 and 4
  2. Do this Combine perpendicular lengths
  3. Result 5
The squared lengths sum to 25. Its square root is 5.
lesson.c
#include <stdio.h>
#include <math.h>

int main(void) {
    printf("%.15g\n", (double) (hypot(3.0, 4.0)));
}
Output
5

Syntax

C 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.

First output line5.0
lesson.c
#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;
}
Output
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

Advertisements

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.

From the programdouble east = 6.0
Result10.000
lesson.c
#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;
}
Output
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.

GivenEast 5 m · north 12 m
Worked result13 m

The perpendicular offsets form the legs of a right triangle.