Library contents

C++ std::hypot

std::hypot returns the length of a vector from its Cartesian components. It scales the calculation to avoid needless intermediate overflow and underflow.

A simple example

std::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.cpp
#include <iostream>
#include <cmath>

int main() {
    std::cout << (std::hypot(3.0, 4.0)) << '\n';
}
Output
5

Syntax

C++ syntax
std::hypot(x, y)
Run this example in C++

Save the program as lesson.cpp. Use C++17 and a Unix-style shell.

c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson

Measure a two-dimensional displacement

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
lesson.cpp
#include <iostream>
#include <cmath>

int main() {
    std::cout << std::hypot(-3.0, 4.0) << '\n';
    std::cout << std::boolalpha << std::isfinite(std::hypot(1e200, 1e200)) << '\n';
    return 0;
}
Output
5
true

A negative component affects direction, while the distance stays nonnegative. The large diagonal below still fits in a double even though its component squares would overflow.

C++ working draft for std::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 programconst double east = 6.0
Result10.000
lesson.cpp
#include <cmath>
#include <cstdio>

int main() {
    const double east = 6.0;
    const double north = 8.0;

    std::printf("%.3f\n", std::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.