Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>`return fabs(a - b) &lt; EPSILON;</p> </blockquote> <p>This is fine if:</p> <ul> <li>the order of magnitude of your inputs don't change much</li> <li>very small numbers of opposite signs can be treated as equal</li> </ul> <p>But otherwise it'll lead you into trouble. Double precision numbers have a resolution of about 16 decimal places. If the two numbers you are comparing are larger in magnitude than EPSILON*1.0E16, then you might as well be saying:</p> <pre><code>return a==b; </code></pre> <p>I'll examine a different approach that assumes you need to worry about the first issue and assume the second is fine your application. A solution would be something like:</p> <pre><code>#define VERYSMALL (1.0E-150) #define EPSILON (1.0E-8) bool AreSame(double a, double b) { double absDiff = fabs(a - b); if (absDiff &lt; VERYSMALL) { return true; } double maxAbs = max(fabs(a) - fabs(b)); return (absDiff/maxAbs) &lt; EPSILON; } </code></pre> <p>This is expensive computationally, but it is sometimes what is called for. This is what we have to do at my company because we deal with an engineering library and inputs can vary by a few dozen orders of magnitude.</p> <p>Anyway, the point is this (and applies to practically every programming problem): Evaluate what your needs are, then come up with a solution to address your needs -- don't assume the easy answer will address your needs. If after your evaluation you find that <code>fabs(a-b) &lt; EPSILON</code> will suffice, perfect -- use it! But be aware of its shortcomings and other possible solutions too.</p>
 

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