4

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
  • 36,841
  • 4
  • 40
  • 60
matthias_buehlmann
  • 4,359
  • 5
  • 30
  • 61
  • 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
  • 16,602
  • 2
  • 20
  • 35