title: Why does adding 0.1 multiple times remain lossless?
body: <p>I know the <code>0.1</code> decimal number cannot be represented exactly with a finite binary number (<a href="http://www.exploringbinary.com/why-0-point-1-does-not-exist-in-floating-point/">explanation</a>), so <code>double n = 0.1</code> will lose some precision and will not be exactly <code>0.1</code>. On the other hand <code>0.5</code> can be represented exactly because it is <code>0.5 = 1/2 = 0.1b</code>.</p>
  
  <p>Having said that it is understandable that adding <code>0.1</code> <strong>three times</strong> will not give exactly <code>0.3</code> so the following code prints <code>false</code>:</p>
  
  <pre><code>double sum = 0, d = 0.1;
  for (int i = 0; i &lt; 3; i++)
      sum += d;
  System.out.println(sum == 0.3); // Prints false, OK
  </code></pre>
  
  <p>But then how is it that adding <code>0.1</code> <strong>five times</strong> will give exactly <code>0.5</code>? The following code prints <code>true</code>:</p>
  
  <pre><code>double sum = 0, d = 0.1;
  for (int i = 0; i &lt; 5; i++)
      sum += d;
  System.out.println(sum == 0.5); // Prints true, WHY?
  </code></pre>
  
  <p>If <code>0.1</code> cannot be represented exactly, how is it that adding it 5 times gives exactly <code>0.5</code> which can be represented precisely?</p>