这个问题在这里已经有了答案:
C++ sqrt function precision for full squares
(3 个回答)
去年关闭。
是否保证,static_cast<int>(std::sqrt(x * x)) == x
对于所有 x*x 不会溢出的正 x?
如果没有,我将如何稳健地计算这些数字的平方根?
最佳答案
来自 cppreference:
std::sqrt
is required by the IEEE standard to be exact. The only other operations required to be exact are the arithmetic operators and the functionstd::fma
. After rounding to the return type (using default rounding mode), the result ofstd::sqrt
is indistinguishable from the infinitely precise result. In other words, the error is less than 0.5 ulp. Other functions, includingstd::pow
, are not so constrained. (ref)
因此,鉴于您的限制,我看不出有任何担心的理由。
关于c++:static_cast<int> std::sqrt(x) 是否总是为平方的正整数给出准确的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63267533/