title: How should I do floating point comparison?
body: <p>I'm currently writing some code where I have something along the lines of:</p>
  
  
  
  <pre class="lang-c# prettyprint-override"><code>double a = SomeCalculation1();
  double b = SomeCalculation2();
  
  if (a &lt; b)
      DoSomething2();
  else if (a &gt; b)
      DoSomething3();
  </code></pre>
  
  <p>And then in other places I may need to do equality:</p>
  
  <pre class="lang-c# prettyprint-override"><code>double a = SomeCalculation3();
  double b = SomeCalculation4();
  
  if (a == 0.0)
     DoSomethingUseful(1 / a);
  if (b == 0.0)
     return 0; // or something else here
  </code></pre>
  
  <p>In short, I have lots of floating point math going on and I need to do various comparisons for conditions. I can't convert it to integer math because such a thing is meaningless in this context.</p>
  
  <p>I've read before that floating point comparisons can be unreliable, since you can have things like this going on:</p>
  
  <pre class="lang-c# prettyprint-override"><code>double a = 1.0 / 3.0;
  double b = a + a + a;
  if ((3 * a) != b)
      Console.WriteLine("Oh no!");
  </code></pre>
  
  <p><strong>In short, I'd like to know: How can I reliably compare floating point numbers (less than, greater than, equality)?</strong></p>
  
  <p>The number range I am using is roughly from 10E-14 to 10E6, so I do need to work with small numbers as well as large.</p>
  
  <p>I've tagged this as language agnostic because I'm interested in how I can accomplish this no matter what language I'm using.</p>