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?
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.
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.
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