Gdb shows incorrect double value

I had strange behavior with my program, in which the double lost accuracy. My cout showed the correct values, but still the behavior was unexpected. Therefore, I debugged and found that even gdb shows unexpected values. The following is just a simplified scenario:

double length =2.11; //gdb shows 2.10 here but prints 2.11 correctly using cout at the end cout<<"length; //It prints 2.11 correctly here 

Often such problems are difficult to find in production scenarios where debugging is not an option, and the only option is to use as many prints as possible. Any suggestions how can I avoid this problem?

+5
source share
2 answers

Assuming IEEE754 double precision floating point, the closest double to 2.11 is a bit smaller

2.109999999999999875655021241982467472553253173828125

std::cout is smart enough to round by default, but gdb seems to truncate to two decimal places.

+6
source

Given the fact that real numbers behave the same way as in your case, I’m afraid there’s nothing to be done about it. You could plan it to avoid this, and create a space for performing equality checks on your double values.

Here are two plausible hacks:

1: [Tried this in a college project] To deal with numbers in the order of 10 ^ -4, use an integer and a coefficient value. Example: to store 1.2345, store as an integer 12345 and multiply as 10000. Now you can print correctly, and this also makes it possible to carry out equality checks.

2: If the accuracy of the double values ​​is already known, you can use the offset. Example: if 2.109999 has an accuracy of 2 decimal places, use something like this: (int) ((2.109999 +.005) * 100). And then type accordingly.

But both of these hacks suggest the following:

1: You control the accuracy of the values. 2: you really need to print accurate values.

+2
source

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


All Articles