documentation of std::hypot说:
Computes the square root of the sum of the squares of x and y, without undue overflow or underflow at intermediate stages of the computation.
我很难想象一个测试用例,其中std :: hypot应该用于平凡的sqrt(x * x y * y).
以下测试显示,std :: hypot比原始计算慢约20倍.
#include
#include
#include
#include
int main(int, char**) {
std::mt19937_64 mt;
const auto samples = 10000000;
std::vector values(2 * samples);
std::uniform_real_distribution urd(-100.0, 100.0);
std::generate_n(values.begin(), 2 * samples, [&]() {return urd(mt); });
std::cout.precision(15);
{
double sum = 0;
auto s = std::chrono::steady_clock::now();
for (auto i = 0; i < 2 * samples; i += 2) {
sum += std::hypot(values[i], values[i + 1]);
}
auto e = std::chrono::steady_clock::now();
std::cout << std::fixed <<:chrono::duration_cast>(e - s).count() << "us --- s:" << sum << std::endl;
}
{
double sum = 0;
auto s = std::chrono::steady_clock::now();
for (auto i = 0; i < 2 * samples; i += 2) {
sum += std::sqrt(values[i]* values[i] + values[i + 1]* values[i + 1]);
}
auto e = std::chrono::steady_clock::now();
std::cout << std::fixed << std::chrono::duration_cast<:chrono::microseconds>(e - s).count() << "us --- s:" << sum << std::endl;
}
}
所以我要求指导,什么时候我必须使用std :: hypot(x,y)通过更快的std :: sqrt(x * x y * y)获得正确的结果.
澄清:当x和y是浮点数时,我正在寻找适用的答案.即比较:
double h = std::hypot(static_cast(x),static_cast(y));
至:
double xx = static_cast(x);
double yy = static_cast(y);
double h = std::sqrt(xx*xx + yy*yy);