Thursday, 31 August 2017

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

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...