c++: does static_cast<int> std::sqrt(x) always give exact result for positive integers that are squares?

Viewed 124

is it guaranteed, that static_cast<int>(std::sqrt(x * x)) == x for all positive x for which x*x does not overflow?

If not, how would I compute the square root of such numbers robustly?

1 Answers

From 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)

So I can't see any reason to worry, given your constraints.

Related