title: C++ How to avoid floating-point arithmetic error
body: <p>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:</p>
  
  <pre><code>for(float value = -2.0; value &lt;= 2.0; value += 0.2)
      std::cout &lt;&lt; value &lt;&lt; std::endl;
  </code></pre>
  
  <p>Here is the output:</p>
  
  <pre><code>-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
  </code></pre>
  
  <p>Why exactly am I getting <code>1.46031e-07</code> instead of <code>0</code>? 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!       </p>