    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Why Floats Are Never Equal</title>
        <link>https://members.accu.org/index.php/articles/2281</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + CVu Journal Vol 28, #4 - September 2016</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c365/">284</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-365/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+365/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Why Floats Are Never Equal</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 08 September 2016 16:14:05 +01:00 or Thu, 08 September 2016 16:14:05 +01:00</p>
<p><strong>Summary:</strong>&nbsp;Silas S. Brown tries his hand at optimising floating point equality comparisons.</p>
<p><strong>Body:</strong>&nbsp;<h2>Optimiser 1, Silas Brown 0</h2>

<p>Youâ€™re probably aware that comparing two floats or doubles for equality is a bad idea due to rounding error. If two numbers which you expect to be equal were calculated in two different ways, the two different calculations will likely have different rounding errors and you donâ€™t quite end up getting an equal result, so you have to do something like:</p>

<pre class="programlisting">
  fabs(b-a) &lt; .0001</pre>

<p>where .0001 is a tolerance chosen appropriately for your application (there are ways of working it out in the general case, but if you know your application then you probably have a good idea of what sort of numbers youâ€™re dealing with). Do use <code>fabs</code> rather than coding it yourself, as many compilers will convert <code>fabs</code> to a single instruction.</p>

<p>I was doing some voluntary programming for a cancer research team <a href="#[1]">[1]</a>, and it involved a thermodynamics calculation on fragments of DNA at different alignments. Once all possible alignments had been checked and we knew which one gave the lowest result, I wanted to display information about it. I had three options:</p>

<ol>
	<li>Calculate display information about ALL the items, store it, and then display only the one we found to be minimum;</li>
	
	<li>Store the loop counter of the minimum item so far so we can go back to it;</li>
	
	<li>Just store the minimum value, then go back through the whole loop and find it again.</li>
</ol>

<p>Option 1 would run slower and moreover would be a memory management hassle to code. Normally I would have picked option 2, but in this case each loop iteration was making incremental changes to quite a few variables along the way, and on the other hand there werenâ€™t very many loop iterations, so I decided on option 3.</p>

<p>Now surely, I thought, this could be the one occasion where it <em>is</em> all right to save a couple of CPU cycles by comparing two floating-point values for equality. After all, the second version of the loop is exactly retracing the steps of the first, with exactly the same formulae and only the addition of some extra display code in between. The rounding error canâ€™t possibly be any different this time, can it?</p>

<p>Wrong.</p>

<p>The extra display code was nothing to do with the floating-point calculation, but it did affect the optimiserâ€™s decisions of which values to keep in registers and which ones to write back to memory. And it turned out the x86 CPU had 80-bit floating-point registers, which were being rounded down to 64-bit (or 32-bit) when writing to memory. So if the optimiser found enough room to keep an intermediate result in a register, it would be kept at 80-bit precision, but if it decided to spill that register to memory to make room for something else, precision would be lost. And optimisers these days have ways of using floating-point registers as holding bays for non-floating point data, so just because the extra code wasnâ€™t doing any floating point itself, didnâ€™t mean it wouldnâ€™t be compiled to something that â€˜wantedâ€™ those registers. The presence of this display code was causing the floating-point registers to be saved out to memory, and precision to be lost, making the equality comparison still wrong even though I was looking at the same C formulae in both cases.</p>

<p>I didnâ€™t spot this bug at first because, when I was developing, I happened to be using a Mac, which is based on BSD. BSD defaults to putting the x86 CPU into a mode where it always rounds its intermediate results, so there is no difference between a result held in a register and one written to memory. So I was getting away with it. But then we tried to run the same code on GNU/Linux, which <em>doesnâ€™t</em> tell the CPU to round, because it prefers accuracy to predictability. And it got stuck in an infinite loop looking for a minimum that didnâ€™t exist.</p>

<p>Of course there are ways to dodge the issue on x86 CPUs. You could find out how to change the CPUâ€™s rounding mode yourself (it involves assembly). Or you could make sure to always use 80-bit variables (usually called â€˜long doubleâ€™ by x86 compilers), although if you donâ€™t need that much precision then the extra memory operations would probably slow you down far more than a â€˜nearly equalâ€™ comparison would (and the same goes for GCCâ€™s <code>-ffloat-store</code> option, which prevents any intermediate floating-point values from being held in registers at all). But what if someone wants to compile your code on some other kind of CPU? Can you be sure that there wonâ€™t be a similar problem?</p>

<p>Floats are <em>never</em> equal. Well they are sometimes, but you donâ€™t know when, even if you think you do. Not unless youâ€™re programming in assembly and you know exactly which intermediate results are held in which registers at which times, and the chances are your application doesnâ€™t make it worth your time to go there. Floats are never equal.</p>

<p>Finally, if you really want to save 2 CPU instructions and are looking for a known minimum, then instead of doing <code>fabs(x-minimum)&lt;.0001</code>, you can first add .0001 to <code>minimum</code> outside the loop, then simply test for <code>x &lt; minimum</code>. Do check this tolerance is appropriate to your application and can be represented by your chosen floating-point precision.</p>

<p>GCC has a warning when you try to compare two floats for equality, but you have to switch it on with the <code>-Wfloat-equal</code> option, which is sadly not included in <code>-Wall</code> or <code>-Wextra</code>.</p>

<h2>Reference</h2>

<p class="bibliomixed"><a id="[1]"></a>[1]	<a href="http://people.ds.cam.ac.uk/ssb22/pooler">http://people.ds.cam.ac.uk/ssb22/pooler</a></p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
