title: Why 0.1 + 0.2 == 0.3 in D?
body: <pre><code>assert(0.1 + 0.2 != 0.3); // shall be true
  </code></pre>
  
  <p>is my favorite check that a language uses native floating point arithmetic.</p>
  
  <h2>C++</h2>
  
  <pre><code>#include &lt;cstdio&gt;
  
  int main()
  {
     printf("%d\n", (0.1 + 0.2 != 0.3));
     return 0;
  }
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>1
  </code></pre>
  
  <p><a href="http://ideone.com/ErBMd" rel="nofollow noreferrer">http://ideone.com/ErBMd</a></p>
  
  <h2>Python</h2>
  
  <pre><code>print(0.1 + 0.2 != 0.3)
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>True
  </code></pre>
  
  <p><a href="http://ideone.com/TuKsd" rel="nofollow noreferrer">http://ideone.com/TuKsd</a></p>
  
  <h2>Other examples</h2>
  
  <ul>
  <li>Java: <a href="http://ideone.com/EPO6X" rel="nofollow noreferrer">http://ideone.com/EPO6X</a></li>
  <li>C#: <a href="http://ideone.com/s14tV" rel="nofollow noreferrer">http://ideone.com/s14tV</a></li>
  </ul>
  
  <p>Why is this not true for D? As understand D uses native floating point numbers. Is this a bug? Do they use some specific number representation? Something else? Pretty confusing.</p>
  
  <h2>D</h2>
  
  <pre><code>import std.stdio;
  
  void main()
  {
     writeln(0.1 + 0.2 != 0.3);
  }
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>false
  </code></pre>
  
  <p><a href="http://ideone.com/mX6zF" rel="nofollow noreferrer">http://ideone.com/mX6zF</a></p>
  
  <hr>
  
  <h2>UPDATE</h2>
  
  <p>Thanks to <a href="https://stackoverflow.com/users/55847/lukeh">LukeH</a>. This is an effect of Floating Point Constant Folding described <a href="http://www.d-programming-language.org/float.html" rel="nofollow noreferrer">there</a>. </p>
  
  <p>Code:</p>
  
  <pre><code>import std.stdio;
  
  void main()
  {
     writeln(0.1 + 0.2 != 0.3); // constant folding is done in real precision
  
     auto a = 0.1;
     auto b = 0.2;
     writeln(a + b != 0.3);     // standard calculation in double precision
  }
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>false
  true
  </code></pre>
  
  <p><a href="http://ideone.com/z6ZLk" rel="nofollow noreferrer">http://ideone.com/z6ZLk</a></p>