C ++ - How to translate double to int correctly

I am currently writing a program that should take the square root word. Since the value that I take from the square root is positive, I just passed it int. So say in the following example:

int i = 16; int j = std::sqrt(i) 

j should be 4.

I am wondering if it is possible that sqrt returns 3.9999999991 instead of 4.000000001 or something else, and the result of j is 3? Are there rules defining floating point behavior? How can I convert this to int correctly?

+5
source share
1 answer

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; 
+3
source

Source: https://habr.com/ru/post/1214766/


All Articles