Almost all widely available hardware uses IETF754 floating point numbers, although C++ does not require it.
Assuming IETF754 floating point numbers and a direct mapping of ::std::sqrt
to the IETF754 floating point square root operation, you are assured of the following:
- 16 and 4 can both be represented exactly in floating point arithmetic - in fact, double precision floating point numbers can represent any 32 bit integer exactly
- the square root returns the result that is closest to being exact
Therefore, your example will work fine.
In general, the problem you have hinted at might happen, but to solve it you have to ask a bigger question: Under which circumstances is a number that is close to integral, really integral?
This is actually harder than it might seem, since you want to compute the floor of the square root, and therefore simply rounding will not work for you. However, once you have answered this question for yourself, implementing a solution should be rather simple. For example:
int i = 16;
int j = std::sqrt(i);
if((j + 1) * (j + 1) == i) j += 1;