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?
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?
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 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)
So I can't see any reason to worry, given your constraints.