Friday 24 August 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...