I'm currently writing a program that needs to take the floor of a square root. Since the value I'm taking the square root of is positive, I just cast it to int. So say for the following example:
int i = 16;
int j = std::sqrt(i)
j should be 4.
I am wondering though, is it possible that sqrt returns 3.9999999991 instead of 4.000000001 or whatever, and the result of j is 3? Is there rules defining floating point behaviour? How can I properly convert this to an int?
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:
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With