+ 2

Can anyone explain this code to me ... Why the output is false?

https://code.sololearn.com/c106m44Qtc72/?ref=app

28th Feb 2019, 8:37 AM
Chandra Prakash Singh Bisht
Chandra Prakash Singh Bisht - avatar
4 Réponses
+ 5
Because floating points are not very accurate. 0.1 is actually 0.10000000000055... 0.2 is 0.20000000000011... 0.3 is 0.29999999999999... 0.1 + 0.2 = 0.30000000000066... By adding a and b you only accumulate that slight error difference into a bigger error. Also those digits are made up, I don't know them to the decimal, but they are close enough.
28th Feb 2019, 9:13 AM
Dennis
Dennis - avatar
28th Feb 2019, 9:15 AM
KrOW
KrOW - avatar
+ 3
That's why you typically don't test for equality of floating point numbers but for |(a+b) - c| < eps for some value of eps around 10^-5 instead. (|x| means the absolute value of x)
28th Feb 2019, 10:53 AM
merkrafter
+ 1
As you may have seen in the C++ tutorial, double data type (8 bytes) are bigger than a float data type (which is 4 bytes). Anyway, if you change the data type of all the variables to float, the output will be true.
28th Feb 2019, 9:24 AM
Mr. Damik
Mr. Damik - avatar