Almost all common equipment uses IETF754 floating point numbers, although C ++ does not require it.
Assuming the IETF754 floating point numbers and the direct mapping ::std::sqrt to the IETF754 square root floating point operation, you are sure of the following:
- 16 and 4 can 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 the exact
So your example will work fine .
In general, the problem that you hinted at may occur, but to solve it you must ask a larger question: under what circumstances is this number close to integral, really integral?
This is actually more complicated than it might seem, since you want to calculate the square root square, and therefore just rounding will not work for you. However, once you have answered this question for yourself, the implementation of the solution should be quite simple. For instance:
int i = 16; int j = std::sqrt(i); if((j + 1) * (j + 1) == i) j += 1;
source share