Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Writing a useful general-purpose floating point <code>IsEqual</code> is very, very hard, if not outright impossible. Your current code will fail badly for <code>a==0</code>. How the method should behave for such cases is really a matter of definition, and arguably the code would best be tailored for the specific domain use case.</p> <p>For this kind of thing, you <em>really, really need</em> a good test suite. That's how I did it for <a href="http://floating-point-gui.de/errors/comparison/" rel="noreferrer">The Floating-Point Guide</a>, this is what I came up with in the end (Java code, should be easy enough to translate):</p> <pre><code>public static boolean nearlyEqual(float a, float b, float epsilon) { final float absA = Math.abs(a); final float absB = Math.abs(b); final float diff = Math.abs(a - b); if (a == b) { // shortcut, handles infinities return true; } else if (a == 0 || b == 0 || diff &lt; Float.MIN_NORMAL) { // a or b is zero or both are extremely close to it // relative error is less meaningful here return diff &lt; (epsilon * Float.MIN_NORMAL); } else { // use relative error return diff / (absA + absB) &lt; epsilon; } } </code></pre> <p>You can also find <a href="http://floating-point-gui.de/errors/comparison/" rel="noreferrer">the test suite on the site</a>.</p> <p><strong>Appendix:</strong> Same code in c# for doubles (as asked in questions)</p> <pre><code>public static bool NearlyEqual(double a, double b, double epsilon) { double absA = Math.Abs(a); double absB = Math.Abs(b); double diff = Math.Abs(a - b); if (a == b) { // shortcut, handles infinities return true; } else if (a == 0 || b == 0 || diff &lt; Double.Epsilon) { // a or b is zero or both are extremely close to it // relative error is less meaningful here return diff &lt; epsilon; } else { // use relative error return diff / (absA + absB) &lt; epsilon; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload