<p>What is the best method for comparing IEEE floats and doubles for equality?  I have heard of several methods, but I wanted to see what the community thought.</p>

[{'answer_id': 21277, 'author': 'DrPizza', 'author_id': 2131, 'author_profile': 'https://Stackoverflow.com/users/2131', 'pm_score': 4, 'selected': True, 'text': '<p>The best approach I think is to compare <a href="http://en.wikipedia.org/wiki/Unit_in_the_last_place" rel="noreferrer">ULPs</a>.</p>\n\n<pre><code>bool is_nan(float f)\n{\n    return (*reinterpret_cast&lt;unsigned __int32*&gt;(&amp;f) &amp; 0x7f800000) == 0x7f800000 &amp;&amp; (*reinterpret_cast&lt;unsigned __int32*&gt;(&amp;f) &amp; 0x007fffff) != 0;\n}\n\nbool is_finite(float f)\n{\n    return (*reinterpret_cast&lt;unsigned __int32*&gt;(&amp;f) &amp; 0x7f800000) != 0x7f800000;\n}\n\n// if this symbol is defined, NaNs are never equal to anything (as is normal in IEEE floating point)\n// if this symbol is not defined, NaNs are hugely different from regular numbers, but might be equal to each other\n#define UNEQUAL_NANS 1\n// if this symbol is defined, infinites are never equal to finite numbers (as they\'re unimaginably greater)\n// if this symbol is not defined, infinities are 1 ULP away from +/- FLT_MAX\n#define INFINITE_INFINITIES 1\n\n// test whether two IEEE floats are within a specified number of representable values of each other\n// This depends on the fact that IEEE floats are properly ordered when treated as signed magnitude integers\nbool equal_float(float lhs, float rhs, unsigned __int32 max_ulp_difference)\n{\n#ifdef UNEQUAL_NANS\n    if(is_nan(lhs) || is_nan(rhs))\n    {\n        return false;\n    }\n#endif\n#ifdef INFINITE_INFINITIES\n    if((is_finite(lhs) &amp;&amp; !is_finite(rhs)) || (!is_finite(lhs) &amp;&amp; is_finite(rhs)))\n    {\n        return false;\n    }\n#endif\n    signed __int32 left(*reinterpret_cast&lt;signed __int32*&gt;(&amp;lhs));\n    // transform signed magnitude ints into 2s complement signed ints\n    if(left &lt; 0)\n    {\n        left = 0x80000000 - left;\n    }\n    signed __int32 right(*reinterpret_cast&lt;signed __int32*&gt;(&amp;rhs));\n    // transform signed magnitude ints into 2s complement signed ints\n    if(right &lt; 0)\n    {\n        right = 0x80000000 - right;\n    }\n    if(static_cast&lt;unsigned __int32&gt;(std::abs(left - right)) &lt;= max_ulp_difference)\n    {\n        return true;\n    }\n    return false;\n}\n</code></pre>\n\n<p>A similar technique can be used for doubles.  The trick is to convert the floats so that they\'re ordered (as if integers) and then just see how different they are.</p>\n\n<p>I have no idea why this damn thing is screwing up my underscores.  Edit: Oh, perhaps that is just an artefact of the preview.  That\'s OK then.</p>\n'}, {'answer_id': 21279, 'author': 'Mat Noguchi', 'author_id': 1799, 'author_profile': 'https://Stackoverflow.com/users/1799', 'pm_score': 0, 'selected': False, 'text': "<p>Oh dear lord please don't interpret the float bits as ints unless you're running on a P6 or earlier.</p>\n"}, {'answer_id': 21291, 'author': 'DrPizza', 'author_id': 2131, 'author_profile': 'https://Stackoverflow.com/users/2131', 'pm_score': 0, 'selected': False, 'text': "<blockquote>\n  <p>Oh dear lord please don't interpret the float bits as ints unless you're running on a P6 or earlier.</p>\n</blockquote>\n\n<p>Even if it causes it to copy from vector registers to integer registers via memory, and even if it stalls the pipeline, it's the best way to do it that I've come across, insofar as it provides the most robust comparisons even in the face of floating point errors.</p>\n\n<p>i.e. it is a price worth paying.</p>\n"}, {'answer_id': 21298, 'author': 'Craig H', 'author_id': 2328, 'author_profile': 'https://Stackoverflow.com/users/2328', 'pm_score': 2, 'selected': False, 'text': '<p>The current version I am using is this</p>\n\n<pre><code>bool is_equals(float A, float B,\n               float maxRelativeError, float maxAbsoluteError)\n{\n\n  if (fabs(A - B) &lt; maxAbsoluteError)\n    return true;\n\n  float relativeError;\n  if (fabs(B) &gt; fabs(A))\n    relativeError = fabs((A - B) / B);\n  else\n    relativeError = fabs((A - B) / A);\n\n  if (relativeError &lt;= maxRelativeError)\n    return true;\n\n  return false;\n}\n</code></pre>\n\n<p>This seems to take care of most problems by combining relative and absolute error tolerance.  Is the ULP approach better?  If so, why?</p>\n'}, {'answer_id': 21307, 'author': 'Mat Noguchi', 'author_id': 1799, 'author_profile': 'https://Stackoverflow.com/users/1799', 'pm_score': 0, 'selected': False, 'text': "<blockquote>\n  <p>it's the best way to do it that I've come across, insofar as it provides the most robust comparisons even in the face of floating point errors.</p>\n</blockquote>\n\n<p>If you have floating point errors you have even more problems than this. Although I guess that is up to personal perspective.</p>\n"}, {'answer_id': 21312, 'author': 'DrPizza', 'author_id': 2131, 'author_profile': 'https://Stackoverflow.com/users/2131', 'pm_score': 0, 'selected': False, 'text': '<blockquote>\n  <p>This seems to take care of most problems by combining relative and absolute error tolerance. Is the ULP approach better? If so, why?</p>\n</blockquote>\n\n<p>ULPs are a direct measure of the "distance" between two floating point numbers.  This means that they don\'t require you to conjure up the relative and absolute error values, nor do you have to make sure to get those values "about right".  With ULPs, you can express directly how close you want the numbers to be, and the same threshold works just as well for small values as for large ones.</p>\n'}, {'answer_id': 21317, 'author': 'DrPizza', 'author_id': 2131, 'author_profile': 'https://Stackoverflow.com/users/2131', 'pm_score': 0, 'selected': False, 'text': "<blockquote>\n  <p>If you have floating point errors you have even more problems than this. Although I guess that is up to personal perspective.</p>\n</blockquote>\n\n<p>Even if we do the numeric analysis to minimize accumulation of error, we can't eliminate it and we can be left with results that ought to be identical (if we were calculating with reals) but differ (because we cannot calculate with reals).</p>\n"}, {'answer_id': 21318, 'author': 'Nick', 'author_id': 1490, 'author_profile': 'https://Stackoverflow.com/users/1490', 'pm_score': 0, 'selected': False, 'text': '<p>If you are looking for two floats to be equal, then they should be identically equal in my opinion.  If you are facing a floating point rounding problem, perhaps a fixed point representation would suit your problem better.</p>\n'}, {'answer_id': 21323, 'author': 'DrPizza', 'author_id': 2131, 'author_profile': 'https://Stackoverflow.com/users/2131', 'pm_score': 0, 'selected': False, 'text': '<blockquote>\n  <p>If you are looking for two floats to be equal, then they should be identically equal in my opinion. If you are facing a floating point rounding problem, perhaps a fixed point representation would suit your problem better.</p>\n</blockquote>\n\n<p>Perhaps we cannot afford the loss of range or performance that such an approach would inflict.</p>\n'}, {'answer_id': 21337, 'author': 'Craig H', 'author_id': 2328, 'author_profile': 'https://Stackoverflow.com/users/2328', 'pm_score': 0, 'selected': False, 'text': '<blockquote>\n  <p>If you are looking for two floats to be equal, then they should be identically equal in my opinion. If you are facing a floating point rounding problem, perhaps a fixed point representation would suit your problem better.</p>\n</blockquote>\n\n<p>Perhaps I should explain the problem better.  In C++, the following code:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nusing namespace std;\n\n\nint main()\n{\n  float a = 1.0;\n  float b = 0.0;\n\n  for(int i=0;i&lt;10;++i)\n  {\n    b+=0.1;\n  }\n\n  if(a != b)\n  {\n    cout &lt;&lt; "Something is wrong" &lt;&lt; endl;\n  }\n\n  return 1;\n}\n</code></pre>\n\n<p>prints the phrase "Something is wrong".  Are you saying that it should?</p>\n'}, {'answer_id': 21374, 'author': 'Nick', 'author_id': 1490, 'author_profile': 'https://Stackoverflow.com/users/1490', 'pm_score': 0, 'selected': False, 'text': '<p>@DrPizza: I am no performance guru but I would expect fixed point operations to be quicker than floating point operations (in most cases).</p>\n\n<p>@Craig H:  Sure.  I\'m totally okay with it printing that.  If a or b store money then they should be represented in fixed point.  I\'m struggling to think of a real world example where such logic ought to be allied to floats.  Things suitable for floats:</p>\n\n<ul>\n<li>weights</li>\n<li>ranks</li>\n<li>distances</li>\n<li>real world values (like from a ADC)</li>\n</ul>\n\n<p>For all these things, either you much then numbers and simply present the results to the user for human interpretation, or you make a comparative statement (even if such a statement is, "this thing is within 0.001 of this other thing").  A comparative statement like mine is only useful in the context of the algorithm: the "within 0.001" part depends on what <em>physical</em> question you\'re asking.  That my 0.02.  Or should I say 2/100ths?</p>\n'}, {'answer_id': 21384, 'author': 'DrPizza', 'author_id': 2131, 'author_profile': 'https://Stackoverflow.com/users/2131', 'pm_score': 1, 'selected': False, 'text': '<blockquote>\n  <p>@DrPizza: I am no performance guru but I would expect fixed point operations to be quicker than floating point operations (in most cases).</p>\n</blockquote>\n\n<p>It rather depends on what you are doing with them.  A fixed-point type with the same range as an IEEE float would be many many times slower (and many times larger).  </p>\n\n<blockquote>\n  <p>Things suitable for floats:</p>\n</blockquote>\n\n<p>3D graphics, physics/engineering, simulation, climate simulation....</p>\n'}, {'answer_id': 21426, 'author': 'Nick', 'author_id': 1490, 'author_profile': 'https://Stackoverflow.com/users/1490', 'pm_score': 0, 'selected': False, 'text': "<blockquote>\n  <p>It rather depends on what you are\n  doing with them. A fixed-point type\n  with the same range as an IEEE float\n  would be many many times slower (and\n  many times larger).</p>\n</blockquote>\n\n<p>Okay, but if I want a infinitesimally small bit-resolution then it's back to my original point: == and != have no meaning in the context of such a problem.</p>\n\n<p>An int lets me express ~10^9 values (regardless of the range) which seems like enough for any situation where I would care about two of them being equal.  And if that's not enough, use a 64-bit OS and you've got about 10^19 distinct values.</p>\n\n<p>I can express values a range of 0 to 10^200 (for example) in an int, it is just the bit-resolution that suffers (resolution would be greater than 1, but, again, no application has that sort of range as well as that sort of resolution).</p>\n\n<p>To summarize, I think in all cases one either is representing a continuum of values, in which case != and == are irrelevant, or one is representing a fixed set of values, which can be mapped to an int (or a another fixed-precision type).</p>\n"}, {'answer_id': 187426, 'author': 'jakobengblom2', 'author_id': 23054, 'author_profile': 'https://Stackoverflow.com/users/23054', 'pm_score': 0, 'selected': False, 'text': "<blockquote>\n  <p>An int lets me express ~10^9 values\n  (regardless of the range) which seems\n  like enough for any situation where I\n  would care about two of them being\n  equal. And if that's not enough, use a\n  64-bit OS and you've got about 10^19\n  distinct values.</p>\n</blockquote>\n\n<p>I have actually hit that limit... I was trying to juggle times in ps and time in clock cycles in a simulation where you easily hit 10^10 cycles.  No matter what I did I very quickly overflowed the puny range of 64-bit integers... 10^19 is not as much as you think it is, gimme 128 bits computing now! </p>\n\n<p>Floats allowed me to get a solution to the mathematical issues, as the values overflowed with lots zeros at the low end. So you basically had a decimal point floating aronud in the number with no loss of precision (I could like with the more limited distinct number of values allowed in the mantissa of a float compared to a 64-bit int, but desperately needed th range!). </p>\n\n<p>And then things converted back to integers to compare etc. </p>\n\n<p>Annoying, and in the end I scrapped the entire attempt and just relied on floats and &lt; and > to get the work done.  Not perfect, but works for the use case envisioned. </p>\n"}, {'answer_id': 10973098, 'author': 'Michael Lehn', 'author_id': 909565, 'author_profile': 'https://Stackoverflow.com/users/909565', 'pm_score': 1, 'selected': False, 'text': '<p>In numerical software you often want to test whether two floating point numbers are <em>exactly</em> equal.  LAPACK is full of examples for such cases.  Sure, the most common case is where you want to test whether a floating point number equals "Zero", "One", "Two", "Half".  If anyone is interested I can pick some algorithms and go more into detail.</p>\n\n<p>Also in BLAS you often want to check whether a floating point number is exactly Zero or One.  For example, the routine dgemv can compute operations of the form</p>\n\n<ul>\n<li>y = beta*y + alpha*A*x</li>\n<li>y = beta*y + alpha*A^T*x</li>\n<li>y = beta*y + alpha*A^H*x</li>\n</ul>\n\n<p>So if beta equals One you have an "plus assignment" and for beta equals Zero a "simple assignment".  So you certainly can cut the computational cost if you give these (common) cases a special treatment.</p>\n\n<p>Sure, you could design the BLAS routines in such a way that you can avoid exact comparisons (e.g. using some flags).  However, the LAPACK is full of examples where it is not possible.</p>\n\n<p>P.S.:</p>\n\n<ul>\n<li><p>There are certainly many cases where you don\'t want check for "is exactly equal".  For many   people this even might be the only case they ever have to deal with.  All I want to point out is that there are other cases too.</p></li>\n<li><p>Although LAPACK is written in Fortran the logic is the same if you are using other programming languages for numerical software.</p></li>\n</ul>\n'}]
['https://Stackoverflow.com/questions/21265', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2328/']