title: floating point equality in Python and in general
body: <p>I have a piece of code that behaves differently depending on whether I go through a dictionary to get conversion factors or whether I use them directly.</p>
  
  <p>The following piece of code will print <code>1.0 == 1.0 -&gt; False</code></p>
  
  <p>But if you replace <code>factors[units_from]</code> with <code>10.0</code> and <code>factors[units_to  ]</code> with <code>1.0 / 2.54</code> it will print <code>1.0 == 1.0 -&gt; True</code></p>
  
  <pre><code>#!/usr/bin/env python
  
  base = 'cm'
  factors = {
      'cm'        : 1.0,
      'mm'        : 10.0,
      'm'         : 0.01,
      'km'        : 1.0e-5,
      'in'        : 1.0 / 2.54,
      'ft'        : 1.0 / 2.54 / 12.0,
      'yd'        : 1.0 / 2.54 / 12.0 / 3.0,
      'mile'      : 1.0 / 2.54 / 12.0 / 5280,
      'lightyear' : 1.0 / 2.54 / 12.0 / 5280 / 5.87849981e12,
  }
  
  # convert 25.4 mm to inches
  val = 25.4
  units_from = 'mm'
  units_to = 'in'
  
  base_value = val / factors[units_from]
  ret = base_value * factors[units_to  ]
  print ret, '==', 1.0, '-&gt;', ret == 1.0
  </code></pre>
  
  <p>Let me first say that I am pretty sure what is going on here.  I have seen it before in C, just never in Python but since Python in implemented in C we're seeing it.</p>
  
  <p>I know that floating point numbers will change values going from a CPU register to cache and back.  I know that comparing what should be two equal variables will return false if one of them was paged out while the other stayed resident in a register.</p>
  
  <p><strong>Questions</strong></p>
  
  <ul>
  <li>What is the best way to avoid problems like this?... In Python or in general.</li>
  <li>Am I doing something completely wrong?</li>
  </ul>
  
  <p><strong>Side Note</strong></p>
  
  <p>This is obviously part of a stripped down example but what I'm trying to do is come with with classes of length, volume, etc that can compare against other objects of the same class but with different units.</p>
  
  <p><strong>Rhetorical Questions</strong></p>
  
  <ul>
  <li>If this is a potentially dangerous problem since it makes programs behave in an undetermanistic matter, should compilers warn or error when they detect that you're checking equality of floats</li>
  <li>Should compilers support an option to replace all float equality checks with a 'close enough' function?</li>
  <li>Do compilers already do this and I just can't find the information.</li>
  </ul>