Saturday 23 July 2016

C++ How to avoid floating-point arithmetic error




I am writing a loop that increments with a float, but I have come across a floating-point arithmetic issue illustrated in the following example:



for(float value = -2.0; value <= 2.0; value += 0.2)
std::cout << value << std::endl;


Here is the output:




-2
-1.8
-1.6
-1.4
-1.2
-1
-0.8
-0.6
-0.4

-0.2
1.46031e-07
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6

1.8


Why exactly am I getting 1.46031e-07 instead of 0? I know this has something to do with floating-point errors, but I can't grasp why it is happening and what I should do to prevent this from happening (if there is a way). Can someone explain (or point me to a link) that will help me understand? Any input is appreciated. Thanks!


Answer



This is because floating point numbers have only a certain discrete precision.



The 0.2 is not really a 0.2, but is internally represented as a slightly different number.



That is why you are seeing a difference.




This is common in all floating point calculations, and you really can't avoid it.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...