Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gdb showing incorrect double value

Tags:

c++

I had a strange behavior with my program in which the double was losing the precision. My cout's were showing correct values but still the behavior was unexpected. Hence i debugged and found even gdb shows unexpected values. Following is only the 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 issues are hard to find on production scenarios where debugging is not an option and the only option is using as many prints as possible. Any suggestions how can i avoid this problem?

like image 910
anurag86 Avatar asked Feb 28 '17 10:02

anurag86


2 Answers

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

2.109999999999999875655021241982467472553253173828125

std::cout is clever enough to round appropriately by default, but gdb appears to be truncating to 2 decimal places.

like image 118
Bathsheba Avatar answered Oct 24 '22 15:10

Bathsheba


Given the fact that real numbers behave as they did in your case, I fear there isn't much to do about it. You could have planned for it to avoid it, and created space to perform equality checks over your double values.

Here are two plausible hacks for you:

1: [Tried this in a college project] To deal with numbers in the order 10^-4, use an integer and a factor value. Example: to store 1.2345, store like integer 12345 and factor as 10000. Now you can print correctly and this also give feasibility to do equality checks also.

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

But both these hacks assume following:

1: You have control on accuracy of values. 2: you really need printing accurate values.

like image 30
vishwarajanand Avatar answered Oct 24 '22 14:10

vishwarajanand