Friday, August 24, 2018

C/C++ floating point issue

I am struggling with a basic floating-point precision issue. Here is the problem:



double d = 0.1;
d += 0.1;
d += 0.1;

d == 0.3 ? std::cout << "yes" : std::cout << "no";


Run the code and you get "no"




I understand that C/C++ store values in binary and that binary storage can not exactly store every value. I also understand that these small errors compound as you do various math operations on them (i.e. d += 0.1;).



My questions is if I do need to test if d == 0.3 (to a reasonable precision.. as is the clear intent of code above)... how do I do that? I hope the answer is not:



if (d > 0.2999 && d < 0.3001) ...


ALSO.. this works




float f = 0.1;
f += 0.1;
f += 0.1;

f == 0.3f ? std::cout << "yes" : std::cout << "no";


but I can find no equivalent "0.3d" in the language.



Thanks

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...