C/C++標準ライブラリで2点間距離 (x1,y1) - (x2,y2) を計算する方法。C99以降またはC++11以降では、sqrt
関数の他にhypot
関数も利用できる。*1
#include <cmath> // C++98 double dist = std::sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); // C++11以降 double dist = std::hypot(x2 - x1, y2 - y1);
#include <math.h> /* C90 */ double dist = sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); // C99以降 double dist = hypot(x2 - x1, y2 - y1);
メモ:hypotは三平方の定理の "hypotenuse"(斜辺)から来ているらしい。他の言語処理系でも同名関数が提供されるケースが多い。
関連URL
- Tippet: No need to square, sum, and sqrt manually anymore
- cppreference std::hypot, hypot, hyopotf, hyopotl
- java - Why hypot() function is so slow? - Stack Overflow
*1:ライブラリ実装依存ではあるが、hypot関数の方はオーバーフロー/アンダーフロー対策がされて高精度に計算される。一方、処理速度の観点ではsqrt関数の方が速い可能性がある。http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libm/src/e_hypot.c なども参考に。