5

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?

Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82
matthias_buehlmann
  • 4,641
  • 6
  • 34
  • 76
  • 1
    You'll need to make sure that `x*x` is a value that can be exactly represented as `double`. This would be true on a system with IEEE 754 `double`s if `x*x` is an `int`. – Nate Eldredge Aug 05 '20 at 15:08

1 Answers1

0

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.

Asteroids With Wings
  • 17,071
  • 2
  • 21
  • 35