c++:static_cast<int> std::sqrt(x) 是否总是为平方的正整数给出准确的结果?

标签 c++ sqrt

这个问题在这里已经有了答案:





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 function std::fma. After rounding to the return type (using default rounding mode), the result of std::sqrt is indistinguishable from the infinitely precise result. In other words, the error is less than 0.5 ulp. Other functions, including std::pow, are not so constrained. (ref)


因此,鉴于您的限制,我看不出有任何担心的理由。

关于c++:static_cast<int> std::sqrt(x) 是否总是为平方的正整数给出准确的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63267533/

相关文章:

c++ - 为什么我的 C++ 程序使用的系统时间多于运行时间?

c++ - 我可以将 Functor 类(重载运算符())传递给需要函数指针的函数吗?如何

nasm - 快速整数 sqrt 上限近似

c - sqrt 仅在参数为非负时定义

c++ - 如何将这个简单的 ruby​​ 脚本翻译成 C++?

C++ 解引用数组

c++使用模板制作最通用的函数

c - C 算法中的平方根问题

sympy - 在 Sympy 中定义符号的范围

c - 计算平方根的奇怪方法