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
- Start with Legs 3 and 4
- Do this Combine perpendicular lengths
- Result 5
#include <iostream>
#include <cmath>
int main() {
std::cout << (std::hypot(3.0, 4.0)) << '\n';
}
5
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.
#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;
}
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
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 <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;
}
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.