<p>What would be the most efficient way to compare two <code>double</code> or two <code>float</code> values?</p>

<p>Simply doing this is not correct:</p>

<pre><code>bool CompareDoubles1 (double A, double B)
{
   return A == B;
}
</code></pre>

<p>But something like:</p>

<pre><code>bool CompareDoubles2 (double A, double B) 
{
   diff = A - B;
   return (diff &lt; EPSILON) &amp;&amp; (-diff &lt; EPSILON);
}
</code></pre>

<p>Seems to waste processing.</p>

<p>Does anyone know a smarter float comparer?</p>

[{'answer_id': 17341, 'author': 'OJ.', 'author_id': 611, 'author_profile': 'https://Stackoverflow.com/users/611', 'pm_score': 8, 'selected': False, 'text': '<p>The comparison with an epsilon value is what most people do (even in game programming).</p>\n\n<p>You should change your implementation a little though:</p>\n\n<pre><code>bool AreSame(double a, double b)\n{\n    return fabs(a - b) &lt; EPSILON;\n}\n</code></pre>\n\n<hr>\n\n<p>Edit: Christer has added a stack of great info on this topic on a <a href="http://realtimecollisiondetection.net/blog/?p=89" rel="noreferrer">recent blog post</a>. Enjoy.</p>\n'}, {'answer_id': 17412, 'author': 'fulmicoton', 'author_id': 446497, 'author_profile': 'https://Stackoverflow.com/users/446497', 'pm_score': 4, 'selected': False, 'text': "<p>The code you wrote is bugged :</p>\n\n<pre><code>return (diff &lt; EPSILON) &amp;&amp; (-diff &gt; EPSILON);\n</code></pre>\n\n<p>The correct code would be :</p>\n\n<pre><code>return (diff &lt; EPSILON) &amp;&amp; (diff &gt; -EPSILON);\n</code></pre>\n\n<p>(...and yes this is different)</p>\n\n<p>I wonder if fabs wouldn't make you lose lazy evaluation in some case. I would say it depends on the compiler. You might want to try both. If they are equivalent in average, take the implementation with fabs.</p>\n\n<p>If you have some info on which of the two float is more likely to be bigger than then other, you can play on the order of the comparison to take better advantage of the lazy evaluation.</p>\n\n<p>Finally you might get better result by inlining this function. Not likely to improve much though...</p>\n\n<p>Edit: OJ, thanks for correcting your code. I erased my comment accordingly</p>\n"}, {'answer_id': 17467, 'author': 'grom', 'author_id': 486, 'author_profile': 'https://Stackoverflow.com/users/486', 'pm_score': 6, 'selected': False, 'text': '<p>For a more in depth approach read <a href="http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm" rel="noreferrer">Comparing floating point numbers</a>. Here is the code snippet from that link:</p>\n\n<pre><code>// Usable AlmostEqual function    \nbool AlmostEqual2sComplement(float A, float B, int maxUlps)    \n{    \n    // Make sure maxUlps is non-negative and small enough that the    \n    // default NAN won\'t compare as equal to anything.    \n    assert(maxUlps &gt; 0 &amp;&amp; maxUlps &lt; 4 * 1024 * 1024);    \n    int aInt = *(int*)&amp;A;    \n    // Make aInt lexicographically ordered as a twos-complement int    \n    if (aInt &lt; 0)    \n        aInt = 0x80000000 - aInt;    \n    // Make bInt lexicographically ordered as a twos-complement int    \n    int bInt = *(int*)&amp;B;    \n    if (bInt &lt; 0)    \n        bInt = 0x80000000 - bInt;    \n    int intDiff = abs(aInt - bInt);    \n    if (intDiff &lt;= maxUlps)    \n        return true;    \n    return false;    \n}\n</code></pre>\n'}, {'answer_id': 18289, 'author': 'Mat Noguchi', 'author_id': 1799, 'author_profile': 'https://Stackoverflow.com/users/1799', 'pm_score': -1, 'selected': False, 'text': "<p>It depends on how precise you want the comparison to be. If you want to compare for exactly the same number, then just go with ==. (You almost never want to do this unless you actually want exactly the same number.) On any decent platform you can also do the following:</p>\n\n<pre><code>diff= a - b; return fabs(diff)&lt;EPSILON;\n</code></pre>\n\n<p>as <code>fabs</code> tends to be pretty fast. By pretty fast I mean it is basically a bitwise AND, so it better be fast.</p>\n\n<p>And integer tricks for comparing doubles and floats are nice but tend to make it more difficult for the various CPU pipelines to handle effectively. And it's definitely not faster on certain in-order architectures these days due to using the stack as a temporary storage area for values that are being used frequently. (Load-hit-store for those who care.)</p>\n"}, {'answer_id': 32061, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>General-purpose comparison of floating-point numbers is generally meaningless. How to compare really depends on a problem at hand. In many problems, numbers are sufficiently discretized to allow comparing them within a given tolerance. Unfortunately, there are just as many problems, where such trick doesn't really work. For one example, consider working with a Heaviside (step) function of a number in question (digital stock options come to mind) when your observations are very close to the barrier. Performing tolerance-based comparison wouldn't do much good, as it would effectively shift the issue from the original barrier to two new ones. Again, there is no general-purpose solution for such problems and the particular solution might require going as far as changing the numerical method in order to achieve stability.</p>\n"}, {'answer_id': 37589, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': "<blockquote>\n  <p>`return fabs(a - b) &lt; EPSILON;</p>\n</blockquote>\n\n<p>This is fine if:</p>\n\n<ul>\n<li>the order of magnitude of your inputs don't change much</li>\n<li>very small numbers of opposite signs can be treated as equal</li>\n</ul>\n\n<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>\n\n<pre><code>return a==b;\n</code></pre>\n\n<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>\n\n<pre><code>#define VERYSMALL  (1.0E-150)\n#define EPSILON    (1.0E-8)\nbool AreSame(double a, double b)\n{\n    double absDiff = fabs(a - b);\n    if (absDiff &lt; VERYSMALL)\n    {\n        return true;\n    }\n\n    double maxAbs  = max(fabs(a) - fabs(b));\n    return (absDiff/maxAbs) &lt; EPSILON;\n}\n</code></pre>\n\n<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>\n\n<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>\n"}, {'answer_id': 37686, 'author': 'Chris de Vries', 'author_id': 3836, 'author_profile': 'https://Stackoverflow.com/users/3836', 'pm_score': 5, 'selected': False, 'text': '<p>The portable way to get epsilon in C++ is</p>\n\n<pre><code>#include &lt;limits&gt;\nstd::numeric_limits&lt;double&gt;::epsilon()\n</code></pre>\n\n<p>Then the comparison function becomes</p>\n\n<pre><code>#include &lt;cmath&gt;\n#include &lt;limits&gt;\n\nbool AreSame(double a, double b) {\n    return std::fabs(a - b) &lt; std::numeric_limits&lt;double&gt;::epsilon();\n}\n</code></pre>\n'}, {'answer_id': 77735, 'author': 'Andrew Stein', 'author_id': 13029, 'author_profile': 'https://Stackoverflow.com/users/13029', 'pm_score': 9, 'selected': False, 'text': "<p>Be extremely careful using any of the other suggestions. It all depends on context.</p>\n<p>I have spent a long time tracing bugs in a system that presumed <code>a==b</code> if <code>|a-b|&lt;epsilon</code>. The underlying problems were:</p>\n<ol>\n<li><p>The implicit presumption in an algorithm that if <code>a==b</code> and <code>b==c</code> then <code>a==c</code>.</p>\n</li>\n<li><p>Using the same epsilon for lines measured in inches and lines measured in mils (.001 inch). That is <code>a==b</code> but <code>1000a!=1000b</code>. (This is why <code>AlmostEqual2sComplement</code> asks for the epsilon or max ULPS).</p>\n</li>\n<li><p>The use of the same epsilon for both the cosine of angles and the length of lines!</p>\n</li>\n<li><p>Using such a compare function to sort items in a collection. (In this case using the builtin C++ operator <code>==</code> for doubles produced correct results.)</p>\n</li>\n</ol>\n<p>Like I said: it all depends on context and the expected size of <code>a</code> and <code>b</code>.</p>\n<p>By the way, <code>std::numeric_limits&lt;double&gt;::epsilon()</code> is the &quot;machine epsilon&quot;. It is the difference between <code>1.0</code> and the next value representable by a double. I guess that it could be used in the compare function but only if the expected values are less than 1. (This is in response to @cdv's answer...)</p>\n<p>Also, if you basically have <code>int</code> arithmetic in <code>doubles</code> (here we use doubles to hold int values in certain cases) your arithmetic will be correct. For example <code>4.0/2.0</code> will be the same as <code>1.0+1.0</code>. This is as long as you do not do things that result in fractions (<code>4.0/3.0</code>) or do not go outside of the size of an int.</p>\n"}, {'answer_id': 253874, 'author': 'mch', 'author_id': 32515, 'author_profile': 'https://Stackoverflow.com/users/32515', 'pm_score': 7, 'selected': False, 'text': '<p>Comparing floating point numbers for depends on the context.  Since even changing the order of operations can produce different results, it is important to know how "equal" you want the numbers to be.</p>\n\n<p><a href="https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition" rel="noreferrer">Comparing floating point numbers</a> by Bruce Dawson is a good place to start when looking at floating point comparison.  </p>\n\n<p>The following definitions are from <a href="http://books.google.ca/books?ei=KRkLSYLZEJ7ktQOX3-ChBQ&amp;id=T89QAAAAMAAJ&amp;dq=%22essentially+equal%22+%22approximately+equal%22+knuth&amp;q=%22essentially+equal%22+%22approximately+equal%22+%22definitely+less+than%22&amp;pgis=1#search" rel="noreferrer">The art of computer programming by Knuth</a>: </p>\n\n<pre><code>bool approximatelyEqual(float a, float b, float epsilon)\n{\n    return fabs(a - b) &lt;= ( (fabs(a) &lt; fabs(b) ? fabs(b) : fabs(a)) * epsilon);\n}\n\nbool essentiallyEqual(float a, float b, float epsilon)\n{\n    return fabs(a - b) &lt;= ( (fabs(a) &gt; fabs(b) ? fabs(b) : fabs(a)) * epsilon);\n}\n\nbool definitelyGreaterThan(float a, float b, float epsilon)\n{\n    return (a - b) &gt; ( (fabs(a) &lt; fabs(b) ? fabs(b) : fabs(a)) * epsilon);\n}\n\nbool definitelyLessThan(float a, float b, float epsilon)\n{\n    return (b - a) &gt; ( (fabs(a) &lt; fabs(b) ? fabs(b) : fabs(a)) * epsilon);\n}\n</code></pre>\n\n<p>Of course, choosing epsilon depends on the context, and determines how equal you want the numbers to be.  </p>\n\n<p>Another method of comparing floating point numbers is to look at the ULP (units in last place) of the numbers.  While not dealing specifically with comparisons, the paper <a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.22.6768" rel="noreferrer">What every computer scientist should know about floating point numbers</a> is a good resource for understanding how floating point works and what the pitfalls are, including what ULP is. </p>\n'}, {'answer_id': 3423299, 'author': 'skrebbel', 'author_id': 103395, 'author_profile': 'https://Stackoverflow.com/users/103395', 'pm_score': 7, 'selected': False, 'text': '<p>I found that the <a href="http://code.google.com/p/googletest/" rel="noreferrer">Google C++ Testing Framework</a> contains a nice cross-platform template-based implementation of AlmostEqual2sComplement which works on both doubles and floats. Given that it is released under the BSD license, using it in your own code should be no problem, as long as you retain the license. I extracted the below code from <s><a href="http://code.google.com/p/googletest/source/browse/trunk/include/gtest/internal/gtest-internal.h" rel="noreferrer">http://code.google.com/p/googletest/source/browse/trunk/include/gtest/internal/gtest-internal.h</a></s> <a href="https://github.com/google/googletest/blob/master/googletest/include/gtest/internal/gtest-internal.h" rel="noreferrer">https://github.com/google/googletest/blob/master/googletest/include/gtest/internal/gtest-internal.h</a> and added the license on top.</p>\n\n<p>Be sure to #define GTEST_OS_WINDOWS to some value (or to change the code where it\'s used to something that fits your codebase - it\'s BSD licensed after all).</p>\n\n<p>Usage example:</p>\n\n<pre><code>double left  = // something\ndouble right = // something\nconst FloatingPoint&lt;double&gt; lhs(left), rhs(right);\n\nif (lhs.AlmostEquals(rhs)) {\n  //they\'re equal!\n}\n</code></pre>\n\n<p>Here\'s the code:</p>\n\n<pre><code>// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee)\n//\n// The Google C++ Testing Framework (Google Test)\n\n\n// This template class serves as a compile-time function from size to\n// type.  It maps a size in bytes to a primitive type with that\n// size. e.g.\n//\n//   TypeWithSize&lt;4&gt;::UInt\n//\n// is typedef-ed to be unsigned int (unsigned integer made up of 4\n// bytes).\n//\n// Such functionality should belong to STL, but I cannot find it\n// there.\n//\n// Google Test uses this class in the implementation of floating-point\n// comparison.\n//\n// For now it only handles UInt (unsigned int) as that\'s all Google Test\n// needs.  Other types can be easily added in the future if need\n// arises.\ntemplate &lt;size_t size&gt;\nclass TypeWithSize {\n public:\n  // This prevents the user from using TypeWithSize&lt;N&gt; with incorrect\n  // values of N.\n  typedef void UInt;\n};\n\n// The specialization for size 4.\ntemplate &lt;&gt;\nclass TypeWithSize&lt;4&gt; {\n public:\n  // unsigned int has size 4 in both gcc and MSVC.\n  //\n  // As base/basictypes.h doesn\'t compile on Windows, we cannot use\n  // uint32, uint64, and etc here.\n  typedef int Int;\n  typedef unsigned int UInt;\n};\n\n// The specialization for size 8.\ntemplate &lt;&gt;\nclass TypeWithSize&lt;8&gt; {\n public:\n#if GTEST_OS_WINDOWS\n  typedef __int64 Int;\n  typedef unsigned __int64 UInt;\n#else\n  typedef long long Int;  // NOLINT\n  typedef unsigned long long UInt;  // NOLINT\n#endif  // GTEST_OS_WINDOWS\n};\n\n\n// This template class represents an IEEE floating-point number\n// (either single-precision or double-precision, depending on the\n// template parameters).\n//\n// The purpose of this class is to do more sophisticated number\n// comparison.  (Due to round-off error, etc, it\'s very unlikely that\n// two floating-points will be equal exactly.  Hence a naive\n// comparison by the == operation often doesn\'t work.)\n//\n// Format of IEEE floating-point:\n//\n//   The most-significant bit being the leftmost, an IEEE\n//   floating-point looks like\n//\n//     sign_bit exponent_bits fraction_bits\n//\n//   Here, sign_bit is a single bit that designates the sign of the\n//   number.\n//\n//   For float, there are 8 exponent bits and 23 fraction bits.\n//\n//   For double, there are 11 exponent bits and 52 fraction bits.\n//\n//   More details can be found at\n//   http://en.wikipedia.org/wiki/IEEE_floating-point_standard.\n//\n// Template parameter:\n//\n//   RawType: the raw floating-point type (either float or double)\ntemplate &lt;typename RawType&gt;\nclass FloatingPoint {\n public:\n  // Defines the unsigned integer type that has the same size as the\n  // floating point number.\n  typedef typename TypeWithSize&lt;sizeof(RawType)&gt;::UInt Bits;\n\n  // Constants.\n\n  // # of bits in a number.\n  static const size_t kBitCount = 8*sizeof(RawType);\n\n  // # of fraction bits in a number.\n  static const size_t kFractionBitCount =\n    std::numeric_limits&lt;RawType&gt;::digits - 1;\n\n  // # of exponent bits in a number.\n  static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount;\n\n  // The mask for the sign bit.\n  static const Bits kSignBitMask = static_cast&lt;Bits&gt;(1) &lt;&lt; (kBitCount - 1);\n\n  // The mask for the fraction bits.\n  static const Bits kFractionBitMask =\n    ~static_cast&lt;Bits&gt;(0) &gt;&gt; (kExponentBitCount + 1);\n\n  // The mask for the exponent bits.\n  static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);\n\n  // How many ULP\'s (Units in the Last Place) we want to tolerate when\n  // comparing two numbers.  The larger the value, the more error we\n  // allow.  A 0 value means that two numbers must be exactly the same\n  // to be considered equal.\n  //\n  // The maximum error of a single floating-point operation is 0.5\n  // units in the last place.  On Intel CPU\'s, all floating-point\n  // calculations are done with 80-bit precision, while double has 64\n  // bits.  Therefore, 4 should be enough for ordinary use.\n  //\n  // See the following article for more details on ULP:\n  // http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm.\n  static const size_t kMaxUlps = 4;\n\n  // Constructs a FloatingPoint from a raw floating-point number.\n  //\n  // On an Intel CPU, passing a non-normalized NAN (Not a Number)\n  // around may change its bits, although the new value is guaranteed\n  // to be also a NAN.  Therefore, don\'t expect this constructor to\n  // preserve the bits in x when x is a NAN.\n  explicit FloatingPoint(const RawType&amp; x) { u_.value_ = x; }\n\n  // Static methods\n\n  // Reinterprets a bit pattern as a floating-point number.\n  //\n  // This function is needed to test the AlmostEquals() method.\n  static RawType ReinterpretBits(const Bits bits) {\n    FloatingPoint fp(0);\n    fp.u_.bits_ = bits;\n    return fp.u_.value_;\n  }\n\n  // Returns the floating-point number that represent positive infinity.\n  static RawType Infinity() {\n    return ReinterpretBits(kExponentBitMask);\n  }\n\n  // Non-static methods\n\n  // Returns the bits that represents this number.\n  const Bits &amp;bits() const { return u_.bits_; }\n\n  // Returns the exponent bits of this number.\n  Bits exponent_bits() const { return kExponentBitMask &amp; u_.bits_; }\n\n  // Returns the fraction bits of this number.\n  Bits fraction_bits() const { return kFractionBitMask &amp; u_.bits_; }\n\n  // Returns the sign bit of this number.\n  Bits sign_bit() const { return kSignBitMask &amp; u_.bits_; }\n\n  // Returns true iff this is NAN (not a number).\n  bool is_nan() const {\n    // It\'s a NAN if the exponent bits are all ones and the fraction\n    // bits are not entirely zeros.\n    return (exponent_bits() == kExponentBitMask) &amp;&amp; (fraction_bits() != 0);\n  }\n\n  // Returns true iff this number is at most kMaxUlps ULP\'s away from\n  // rhs.  In particular, this function:\n  //\n  //   - returns false if either number is (or both are) NAN.\n  //   - treats really large numbers as almost equal to infinity.\n  //   - thinks +0.0 and -0.0 are 0 DLP\'s apart.\n  bool AlmostEquals(const FloatingPoint&amp; rhs) const {\n    // The IEEE standard says that any comparison operation involving\n    // a NAN must return false.\n    if (is_nan() || rhs.is_nan()) return false;\n\n    return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_)\n        &lt;= kMaxUlps;\n  }\n\n private:\n  // The data type used to store the actual floating-point number.\n  union FloatingPointUnion {\n    RawType value_;  // The raw floating-point number.\n    Bits bits_;      // The bits that represent the number.\n  };\n\n  // Converts an integer from the sign-and-magnitude representation to\n  // the biased representation.  More precisely, let N be 2 to the\n  // power of (kBitCount - 1), an integer x is represented by the\n  // unsigned number x + N.\n  //\n  // For instance,\n  //\n  //   -N + 1 (the most negative number representable using\n  //          sign-and-magnitude) is represented by 1;\n  //   0      is represented by N; and\n  //   N - 1  (the biggest number representable using\n  //          sign-and-magnitude) is represented by 2N - 1.\n  //\n  // Read http://en.wikipedia.org/wiki/Signed_number_representations\n  // for more details on signed number representations.\n  static Bits SignAndMagnitudeToBiased(const Bits &amp;sam) {\n    if (kSignBitMask &amp; sam) {\n      // sam represents a negative number.\n      return ~sam + 1;\n    } else {\n      // sam represents a positive number.\n      return kSignBitMask | sam;\n    }\n  }\n\n  // Given two numbers in the sign-and-magnitude representation,\n  // returns the distance between them as an unsigned number.\n  static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &amp;sam1,\n                                                     const Bits &amp;sam2) {\n    const Bits biased1 = SignAndMagnitudeToBiased(sam1);\n    const Bits biased2 = SignAndMagnitudeToBiased(sam2);\n    return (biased1 &gt;= biased2) ? (biased1 - biased2) : (biased2 - biased1);\n  }\n\n  FloatingPointUnion u_;\n};\n</code></pre>\n\n<p>EDIT: This post is 4 years old. It\'s probably still valid, and the code is nice, but some people found improvements. Best go get the latest version of <code>AlmostEquals</code> right from the Google Test source code, and not the one I pasted up here.</p>\n'}, {'answer_id': 3432677, 'author': 'Boojum', 'author_id': 37555, 'author_profile': 'https://Stackoverflow.com/users/37555', 'pm_score': 1, 'selected': False, 'text': '<p>I\'d be very wary of any of these answers that involves floating point subtraction (e.g., fabs(a-b) &lt; epsilon).  First, the floating point numbers become more sparse at greater magnitudes and at high enough magnitudes where the spacing is greater than epsilon, you might as well just be doing a == b.  Second, subtracting two very close floating point numbers (as these will tend to be, given that you\'re looking for near equality) is exactly how you get <a href="http://en.wikipedia.org/wiki/Catastrophic_cancellation" rel="nofollow noreferrer">catastrophic cancellation</a>.</p>\n\n<p>While not portable, I think grom\'s answer does the best job of avoiding these issues.</p>\n'}, {'answer_id': 6874157, 'author': 'Don Reba', 'author_id': 49329, 'author_profile': 'https://Stackoverflow.com/users/49329', 'pm_score': 2, 'selected': False, 'text': '<p>Unfortunately, even your "wasteful" code is incorrect. EPSILON is the smallest value that could be added to <strong>1.0</strong> and change its value. The value <strong>1.0</strong> is very important — larger numbers do not change when added to EPSILON. Now, you can scale this value to the numbers you are comparing to tell whether they are different or not. The correct expression for comparing two doubles is:</p>\n\n<pre><code>if (fabs(a - b) &lt;= DBL_EPSILON * fmax(fabs(a), fabs(b)))\n{\n    // ...\n}\n</code></pre>\n\n<p>This is at a minimum. In general, though, you would want to account for noise in your calculations and ignore a few of the least significant bits, so a more realistic comparison would look like:</p>\n\n<pre><code>if (fabs(a - b) &lt;= 16 * DBL_EPSILON * fmax(fabs(a), fabs(b)))\n{\n    // ...\n}\n</code></pre>\n\n<p>If comparison performance is very important to you and you know the range of your values, then you should use fixed-point numbers instead.</p>\n'}, {'answer_id': 7394933, 'author': 'Steve Hollasch', 'author_id': 566185, 'author_profile': 'https://Stackoverflow.com/users/566185', 'pm_score': 3, 'selected': False, 'text': '<p>As others have pointed out, using a fixed-exponent epsilon (such as 0.0000001) will be <em>useless</em> for values away from the epsilon value. For example, if your two values are 10000.000977 and 10000, then there are <strong>NO</strong> 32-bit floating-point values between these two numbers -- 10000 and 10000.000977 are as close as you can possibly get without being bit-for-bit identical. Here, an epsilon of less than 0.0009 is meaningless; you might as well use the straight equality operator.</p>\n\n<p>Likewise, as the two values approach epsilon in size, the relative error grows to 100%.</p>\n\n<p>Thus, trying to mix a fixed point number such as 0.00001 with floating-point values (where the exponent is arbitrary) is a pointless exercise. This will only ever work if you can be assured that the operand values lie within a narrow domain (that is, close to some specific exponent), and if you properly select an epsilon value for that specific test. If you pull a number out of the air ("Hey! 0.00001 is small, so that must be good!"), you\'re doomed to numerical errors. I\'ve spent plenty of time debugging bad numerical code where some poor schmuck tosses in random epsilon values to make yet another test case work.</p>\n\n<p>If you do numerical programming of any kind and believe you need to reach for fixed-point epsilons, <strong>READ BRUCE\'S ARTICLE ON COMPARING FLOATING-POINT NUMBERS</strong>.</p>\n\n<p><a href="http://www.cygnus-software.com/papers/comparingfloats/Comparing%20floating%20point%20numbers.htm">Comparing Floating Point Numbers</a></p>\n'}, {'answer_id': 9025280, 'author': 'WaterbugDesign', 'author_id': 1171153, 'author_profile': 'https://Stackoverflow.com/users/1171153', 'pm_score': 2, 'selected': False, 'text': '<p>My class based on previously posted answers. Very similar to Google\'s code but I use a bias which pushes all NaN values above 0xFF000000. That allows a faster check for NaN.</p>\n\n<p>This code is meant to demonstrate the concept, not be a general solution. Google\'s code already shows how to compute all the platform specific values and I didn\'t want to duplicate all that. I\'ve done limited testing on this code.</p>\n\n<pre><code>typedef unsigned int   U32;\n//  Float           Memory          Bias (unsigned)\n//  -----           ------          ---------------\n//   NaN            0xFFFFFFFF      0xFF800001\n//   NaN            0xFF800001      0xFFFFFFFF\n//  -Infinity       0xFF800000      0x00000000 ---\n//  -3.40282e+038   0xFF7FFFFF      0x00000001    |\n//  -1.40130e-045   0x80000001      0x7F7FFFFF    |\n//  -0.0            0x80000000      0x7F800000    |--- Valid &lt;= 0xFF000000.\n//   0.0            0x00000000      0x7F800000    |    NaN &gt; 0xFF000000\n//   1.40130e-045   0x00000001      0x7F800001    |\n//   3.40282e+038   0x7F7FFFFF      0xFEFFFFFF    |\n//   Infinity       0x7F800000      0xFF000000 ---\n//   NaN            0x7F800001      0xFF000001\n//   NaN            0x7FFFFFFF      0xFF7FFFFF\n//\n//   Either value of NaN returns false.\n//   -Infinity and +Infinity are not "close".\n//   -0 and +0 are equal.\n//\nclass CompareFloat{\npublic:\n    union{\n        float     m_f32;\n        U32       m_u32;\n    };\n    static bool   CompareFloat::IsClose( float A, float B, U32 unitsDelta = 4 )\n                  {\n                      U32    a = CompareFloat::GetBiased( A );\n                      U32    b = CompareFloat::GetBiased( B );\n\n                      if ( (a &gt; 0xFF000000) || (b &gt; 0xFF000000) )\n                      {\n                          return( false );\n                      }\n                      return( (static_cast&lt;U32&gt;(abs( a - b ))) &lt; unitsDelta );\n                  }\n    protected:\n    static U32    CompareFloat::GetBiased( float f )\n                  {\n                      U32    r = ((CompareFloat*)&amp;f)-&gt;m_u32;\n\n                      if ( r &amp; 0x80000000 )\n                      {\n                          return( ~r - 0x007FFFFF );\n                      }\n                      return( r + 0x7F800000 );\n                  }\n};\n</code></pre>\n'}, {'answer_id': 10973460, 'author': 'Michael Lehn', 'author_id': 909565, 'author_profile': 'https://Stackoverflow.com/users/909565', 'pm_score': 0, 'selected': False, 'text': '<p>There are actually cases in numerical software where you want to check whether two floating point numbers are <em>exactly</em> equal.  I posted this on a similar question</p>\n\n<p><a href="https://stackoverflow.com/a/10973098/1447411">https://stackoverflow.com/a/10973098/1447411</a></p>\n\n<p>So you can not say that "CompareDoubles1" is wrong in general.</p>\n'}, {'answer_id': 15012792, 'author': 'Shafik Yaghmour', 'author_id': 1708801, 'author_profile': 'https://Stackoverflow.com/users/1708801', 'pm_score': 5, 'selected': False, 'text': '<p>Realizing this is an old thread but this article is one of the most straight forward ones I have found on comparing floating point numbers and if you want to explore more it has more detailed references as well and it the main site covers a complete range of issues dealing with floating point numbers <a href="http://floating-point-gui.de/errors/comparison/">The Floating-Point Guide :Comparison</a>.</p>\n\n<p>We can find a somewhat more practical article in <a href="http://realtimecollisiondetection.net/blog/?p=89">Floating-point tolerances revisited</a> and notes there is <em>absolute tolerance</em> test, which boils down to this in C++:</p>\n\n<pre><code>bool absoluteToleranceCompare(double x, double y)\n{\n    return std::fabs(x - y) &lt;= std::numeric_limits&lt;double&gt;::epsilon() ;\n}\n</code></pre>\n\n<p>and <em>relative tolerance</em> test:</p>\n\n<pre><code>bool relativeToleranceCompare(double x, double y)\n{\n    double maxXY = std::max( std::fabs(x) , std::fabs(y) ) ;\n    return std::fabs(x - y) &lt;= std::numeric_limits&lt;double&gt;::epsilon()*maxXY ;\n}\n</code></pre>\n\n<p>The article notes that the absolute test fails when <code>x</code> and <code>y</code> are large and fails in the relative case when they are small. Assuming he absolute and relative tolerance is the same a combined test would look like this:</p>\n\n<pre><code>bool combinedToleranceCompare(double x, double y)\n{\n    double maxXYOne = std::max( { 1.0, std::fabs(x) , std::fabs(y) } ) ;\n\n    return std::fabs(x - y) &lt;= std::numeric_limits&lt;double&gt;::epsilon()*maxXYOne ;\n}\n</code></pre>\n'}, {'answer_id': 18518064, 'author': 'Tomilov Anatoliy', 'author_id': 1430927, 'author_profile': 'https://Stackoverflow.com/users/1430927', 'pm_score': 0, 'selected': False, 'text': '<p>In terms of the scale of quantities:</p>\n\n<p>If <code>epsilon</code> is the small fraction of the magnitude of quantity (i.e. relative value) in some certain physical sense and <code>A</code> and <code>B</code> types is comparable in the same sense, than I think, that the following is quite correct:</p>\n\n<pre><code>#include &lt;limits&gt;\n#include &lt;iomanip&gt;\n#include &lt;iostream&gt;\n\n#include &lt;cmath&gt;\n#include &lt;cstdlib&gt;\n#include &lt;cassert&gt;\n\ntemplate&lt; typename A, typename B &gt;\ninline\nbool close_enough(A const &amp; a, B const &amp; b,\n                  typename std::common_type&lt; A, B &gt;::type const &amp; epsilon)\n{\n    using std::isless;\n    assert(isless(0, epsilon)); // epsilon is a part of the whole quantity\n    assert(isless(epsilon, 1));\n    using std::abs;\n    auto const delta = abs(a - b);\n    auto const x = abs(a);\n    auto const y = abs(b);\n    // comparable generally and |a - b| &lt; eps * (|a| + |b|) / 2\n    return isless(epsilon * y, x) &amp;&amp; isless(epsilon * x, y) &amp;&amp; isless((delta + delta) / (x + y), epsilon);\n}\n\nint main()\n{\n    std::cout &lt;&lt; std::boolalpha &lt;&lt; close_enough(0.9, 1.0, 0.1) &lt;&lt; std::endl;\n    std::cout &lt;&lt; std::boolalpha &lt;&lt; close_enough(1.0, 1.1, 0.1) &lt;&lt; std::endl;\n    std::cout &lt;&lt; std::boolalpha &lt;&lt; close_enough(1.1,    1.2,    0.01) &lt;&lt; std::endl;\n    std::cout &lt;&lt; std::boolalpha &lt;&lt; close_enough(1.0001, 1.0002, 0.01) &lt;&lt; std::endl;\n    std::cout &lt;&lt; std::boolalpha &lt;&lt; close_enough(1.0, 0.01, 0.1) &lt;&lt; std::endl;\n    return EXIT_SUCCESS;\n}\n</code></pre>\n'}, {'answer_id': 20345782, 'author': 'Vijay', 'author_id': 674342, 'author_profile': 'https://Stackoverflow.com/users/674342', 'pm_score': -1, 'selected': False, 'text': '<p>My way may not be correct but useful</p>\n\n<p>Convert both float to strings and then do string compare</p>\n\n<pre><code>bool IsFlaotEqual(float a, float b, int decimal)\n{\n    TCHAR form[50] = _T("");\n    _stprintf(form, _T("%%.%df"), decimal);\n\n\n    TCHAR a1[30] = _T(""), a2[30] = _T("");\n    _stprintf(a1, form, a);\n    _stprintf(a2, form, b);\n\n    if( _tcscmp(a1, a2) == 0 )\n        return true;\n\n    return false;\n\n}\n</code></pre>\n\n<p>operator overlaoding can also be done</p>\n'}, {'answer_id': 22161983, 'author': 'Murphy78', 'author_id': 3331297, 'author_profile': 'https://Stackoverflow.com/users/3331297', 'pm_score': -1, 'selected': False, 'text': "<pre><code>/// testing whether two doubles are almost equal. We consider two doubles\n/// equal if the difference is within the range [0, epsilon).\n///\n/// epsilon: a positive number (supposed to be small)\n///\n/// if either x or y is 0, then we are comparing the absolute difference to\n/// epsilon.\n/// if both x and y are non-zero, then we are comparing the relative difference\n/// to epsilon.\nbool almost_equal(double x, double y, double epsilon)\n{\n    double diff = x - y;\n    if (x != 0 &amp;&amp; y != 0){\n        diff = diff/y; \n    }\n\n    if (diff &lt; epsilon &amp;&amp; -1.0*diff &lt; epsilon){\n        return true;\n    }\n    return false;\n}\n</code></pre>\n\n<p>I used this function for my small project and it works, but note the following:</p>\n\n<p>Double precision error can create a surprise for you. Let's say epsilon = 1.0e-6, then 1.0 and 1.000001 should NOT be considered equal according to the above code, but on my machine the function considers them to be equal, this is because 1.000001 can not be precisely translated to a binary format, it is probably 1.0000009xxx. I test it with 1.0 and 1.0000011 and this time I get the expected result.</p>\n"}, {'answer_id': 35244528, 'author': 'Daniel Laügt', 'author_id': 5229914, 'author_profile': 'https://Stackoverflow.com/users/5229914', 'pm_score': -1, 'selected': False, 'text': '<p>You cannot compare two <code>double</code> with a fixed <code>EPSILON</code>. Depending on the value of <code>double</code>, <code>EPSILON</code> varies.</p>\n\n<p>A better double comparison would be:</p>\n\n<pre><code>bool same(double a, double b)\n{\n  return std::nextafter(a, std::numeric_limits&lt;double&gt;::lowest()) &lt;= b\n    &amp;&amp; std::nextafter(a, std::numeric_limits&lt;double&gt;::max()) &gt;= b;\n}\n</code></pre>\n'}, {'answer_id': 39523514, 'author': 'André Sousa', 'author_id': 3746290, 'author_profile': 'https://Stackoverflow.com/users/3746290', 'pm_score': 0, 'selected': False, 'text': '<p>In a more generic way:</p>\n<pre class="lang-cpp prettyprint-override"><code>template &lt;typename T&gt;\nbool compareNumber(const T&amp; a, const T&amp; b) {\n    return std::abs(a - b) &lt; std::numeric_limits&lt;T&gt;::epsilon();\n}\n</code></pre>\n<p>Note:<br>\nAs pointed out by @SirGuy, this approach is flawed.\nI am leaving this answer here as an example not to follow.</p>\n'}, {'answer_id': 40579157, 'author': 'RadioTransmission', 'author_id': 6909917, 'author_profile': 'https://Stackoverflow.com/users/6909917', 'pm_score': -1, 'selected': False, 'text': '<p>Why not perform bitwise XOR? Two floating point numbers are equal if their corresponding bits are equal. I think, the decision to place the exponent bits before mantissa was made to speed up comparison of two floats.\nI think, many answers here are missing the point of epsilon comparison. Epsilon value only depends on to what precision floating point numbers are compared. For example, after doing some arithmetic with floats you get two numbers: 2.5642943554342 and 2.5642943554345. They are not equal, but for the solution only 3 decimal digits matter so then they are equal: 2.564 and 2.564. In this case you choose epsilon equal to 0.001. Epsilon comparison is also possible with bitwise XOR. Correct me if I am wrong.</p>\n'}, {'answer_id': 41405501, 'author': 'Shital Shah', 'author_id': 207661, 'author_profile': 'https://Stackoverflow.com/users/207661', 'pm_score': 5, 'selected': False, 'text': '<p>I ended up spending quite some time going through material in this great thread. I doubt everyone wants to spend so much time so I would highlight the summary of what I learned and the solution I implemented.</p>\n\n<p><strong>Quick Summary</strong></p>\n\n<ol>\n<li>Is 1e-8 approximately same as 1e-16? If you are looking at noisy sensor data then probably yes but if you are doing molecular simulation then may be not! Bottom line: You always need to think of <em>tolerance</em> value in context of specific function call and not just make it generic app-wide hard-coded constant.</li>\n<li>For general library functions, it\'s still nice to have parameter with <em>default tolerance</em>. A typical choice is <code>numeric_limits::epsilon()</code> which is same as FLT_EPSILON in float.h. This is however problematic because epsilon for comparing values like 1.0 is not same as epsilon for values like 1E9. The FLT_EPSILON is defined for 1.0.</li>\n<li>The obvious implementation to check if number is within tolerance is <code>fabs(a-b) &lt;= epsilon</code> however this doesn\'t work because default epsilon is defined for 1.0. We need to scale epsilon up or down in terms of a and b.</li>\n<li>There are two solution to this problem: either you set epsilon proportional to <code>max(a,b)</code> or you can get next representable numbers around a and then see if b falls into that range. The former is called "relative" method and later is called ULP method.</li>\n<li>Both methods actually fails anyway when comparing with 0. In this case, application must supply correct tolerance.</li>\n</ol>\n\n<p><strong>Utility Functions Implementation (C++11)</strong></p>\n\n<pre><code>//implements relative method - do not use for comparing with zero\n//use this most of the time, tolerance needs to be meaningful in your context\ntemplate&lt;typename TReal&gt;\nstatic bool isApproximatelyEqual(TReal a, TReal b, TReal tolerance = std::numeric_limits&lt;TReal&gt;::epsilon())\n{\n    TReal diff = std::fabs(a - b);\n    if (diff &lt;= tolerance)\n        return true;\n\n    if (diff &lt; std::fmax(std::fabs(a), std::fabs(b)) * tolerance)\n        return true;\n\n    return false;\n}\n\n//supply tolerance that is meaningful in your context\n//for example, default tolerance may not work if you are comparing double with float\ntemplate&lt;typename TReal&gt;\nstatic bool isApproximatelyZero(TReal a, TReal tolerance = std::numeric_limits&lt;TReal&gt;::epsilon())\n{\n    if (std::fabs(a) &lt;= tolerance)\n        return true;\n    return false;\n}\n\n\n//use this when you want to be on safe side\n//for example, don\'t start rover unless signal is above 1\ntemplate&lt;typename TReal&gt;\nstatic bool isDefinitelyLessThan(TReal a, TReal b, TReal tolerance = std::numeric_limits&lt;TReal&gt;::epsilon())\n{\n    TReal diff = a - b;\n    if (diff &lt; tolerance)\n        return true;\n\n    if (diff &lt; std::fmax(std::fabs(a), std::fabs(b)) * tolerance)\n        return true;\n\n    return false;\n}\ntemplate&lt;typename TReal&gt;\nstatic bool isDefinitelyGreaterThan(TReal a, TReal b, TReal tolerance = std::numeric_limits&lt;TReal&gt;::epsilon())\n{\n    TReal diff = a - b;\n    if (diff &gt; tolerance)\n        return true;\n\n    if (diff &gt; std::fmax(std::fabs(a), std::fabs(b)) * tolerance)\n        return true;\n\n    return false;\n}\n\n//implements ULP method\n//use this when you are only concerned about floating point precision issue\n//for example, if you want to see if a is 1.0 by checking if its within\n//10 closest representable floating point numbers around 1.0.\ntemplate&lt;typename TReal&gt;\nstatic bool isWithinPrecisionInterval(TReal a, TReal b, unsigned int interval_size = 1)\n{\n    TReal min_a = a - (a - std::nextafter(a, std::numeric_limits&lt;TReal&gt;::lowest())) * interval_size;\n    TReal max_a = a + (std::nextafter(a, std::numeric_limits&lt;TReal&gt;::max()) - a) * interval_size;\n\n    return min_a &lt;= b &amp;&amp; max_a &gt;= b;\n}\n</code></pre>\n'}, {'answer_id': 44210773, 'author': 'Chunde  Huang', 'author_id': 3308831, 'author_profile': 'https://Stackoverflow.com/users/3308831', 'pm_score': 0, 'selected': False, 'text': '<p>I use this code:</p>\n\n<pre><code>bool AlmostEqual(double v1, double v2)\n    {\n        return (std::fabs(v1 - v2) &lt; std::fabs(std::min(v1, v2)) * std::numeric_limits&lt;double&gt;::epsilon());\n    }\n</code></pre>\n'}, {'answer_id': 47514895, 'author': 'Chameleon', 'author_id': 1438465, 'author_profile': 'https://Stackoverflow.com/users/1438465', 'pm_score': -1, 'selected': False, 'text': "<p>I write this for java, but maybe you find it useful. It uses longs instead of doubles, but takes care of NaNs, subnormals, etc.</p>\n\n<pre><code>public static boolean equal(double a, double b) {\n    final long fm = 0xFFFFFFFFFFFFFL;       // fraction mask\n    final long sm = 0x8000000000000000L;    // sign mask\n    final long cm = 0x8000000000000L;       // most significant decimal bit mask\n    long c = Double.doubleToLongBits(a), d = Double.doubleToLongBits(b);        \n    int ea = (int) (c &gt;&gt; 52 &amp; 2047), eb = (int) (d &gt;&gt; 52 &amp; 2047);\n    if (ea == 2047 &amp;&amp; (c &amp; fm) != 0 || eb == 2047 &amp;&amp; (d &amp; fm) != 0) return false;   // NaN \n    if (c == d) return true;                            // identical - fast check\n    if (ea == 0 &amp;&amp; eb == 0) return true;                // ±0 or subnormals\n    if ((c &amp; sm) != (d &amp; sm)) return false;             // different signs\n    if (abs(ea - eb) &gt; 1) return false;                 // b &gt; 2*a or a &gt; 2*b\n    d &lt;&lt;= 12; c &lt;&lt;= 12;\n    if (ea &lt; eb) c = c &gt;&gt; 1 | sm;\n    else if (ea &gt; eb) d = d &gt;&gt; 1 | sm;\n    c -= d;\n    return c &lt; 65536 &amp;&amp; c &gt; -65536;     // don't use abs(), because:\n    // There is a posibility c=0x8000000000000000 which cannot be converted to positive\n}\npublic static boolean zero(double a) { return (Double.doubleToLongBits(a) &gt;&gt; 52 &amp; 2047) &lt; 3; }\n</code></pre>\n\n<p>Keep in mind that after a number of floating-point operations, number can be very different from what we expect. There is no code to fix that.</p>\n"}, {'answer_id': 50997465, 'author': 'Steve Hollasch', 'author_id': 566185, 'author_profile': 'https://Stackoverflow.com/users/566185', 'pm_score': 3, 'selected': False, 'text': '<p>Here\'s proof that using <code>std::numeric_limits::epsilon()</code> is not the answer — it fails for values greater than one:</p>\n\n<p>Proof of my comment above:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;limits&gt;\n\ndouble ItoD (__int64 x) {\n    // Return double from 64-bit hexadecimal representation.\n    return *(reinterpret_cast&lt;double*&gt;(&amp;x));\n}\n\nvoid test (__int64 ai, __int64 bi) {\n    double a = ItoD(ai), b = ItoD(bi);\n    bool close = std::fabs(a-b) &lt; std::numeric_limits&lt;double&gt;::epsilon();\n    printf ("%.16f and %.16f %s close.\\n", a, b, close ? "are " : "are not");\n}\n\nint main()\n{\n    test (0x3fe0000000000000L,\n          0x3fe0000000000001L);\n\n    test (0x3ff0000000000000L,\n          0x3ff0000000000001L);\n}\n</code></pre>\n\n<p>Running yields this output:</p>\n\n<pre><code>0.5000000000000000 and 0.5000000000000001 are  close.\n1.0000000000000000 and 1.0000000000000002 are not close.\n</code></pre>\n\n<p>Note that in the second case (one and just larger than one), the two input values are as close as they can possibly be, and still compare as not close. Thus, for values greater than 1.0, you might as well just use an equality test. Fixed epsilons will not save you when comparing floating-point values.</p>\n'}, {'answer_id': 51015912, 'author': 'Dana Yan', 'author_id': 4472316, 'author_profile': 'https://Stackoverflow.com/users/4472316', 'pm_score': 3, 'selected': False, 'text': '<p><a href="http://doc.qt.io/qt-5/qtglobal.html#qFuzzyCompare" rel="nofollow noreferrer">Qt</a> implements two functions, maybe you can learn from them:</p>\n\n<pre><code>static inline bool qFuzzyCompare(double p1, double p2)\n{\n    return (qAbs(p1 - p2) &lt;= 0.000000000001 * qMin(qAbs(p1), qAbs(p2)));\n}\n\nstatic inline bool qFuzzyCompare(float p1, float p2)\n{\n    return (qAbs(p1 - p2) &lt;= 0.00001f * qMin(qAbs(p1), qAbs(p2)));\n}\n</code></pre>\n\n<p>And you may need the following functions, since    </p>\n\n<blockquote>\n  <p>Note that comparing values where either p1 or p2 is 0.0 will not work,\n  nor does comparing values where one of the values is NaN or infinity.\n  If one of the values is always 0.0, use qFuzzyIsNull instead. If one\n  of the values is likely to be 0.0, one solution is to add 1.0 to both\n  values.</p>\n</blockquote>\n\n<pre><code>static inline bool qFuzzyIsNull(double d)\n{\n    return qAbs(d) &lt;= 0.000000000001;\n}\n\nstatic inline bool qFuzzyIsNull(float f)\n{\n    return qAbs(f) &lt;= 0.00001f;\n}\n</code></pre>\n'}, {'answer_id': 59402500, 'author': 'Prashant Nidgunde', 'author_id': 3351974, 'author_profile': 'https://Stackoverflow.com/users/3351974', 'pm_score': 0, 'selected': False, 'text': '<p>Found another interesting implementation on: <a href="https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon" rel="nofollow noreferrer">https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon</a></p>\n\n<pre><code>#include &lt;cmath&gt;\n#include &lt;limits&gt;\n#include &lt;iomanip&gt;\n#include &lt;iostream&gt;\n#include &lt;type_traits&gt;\n#include &lt;algorithm&gt;\n\n\n\ntemplate&lt;class T&gt;\ntypename std::enable_if&lt;!std::numeric_limits&lt;T&gt;::is_integer, bool&gt;::type\n    almost_equal(T x, T y, int ulp)\n{\n    // the machine epsilon has to be scaled to the magnitude of the values used\n    // and multiplied by the desired precision in ULPs (units in the last place)\n    return std::fabs(x-y) &lt;= std::numeric_limits&lt;T&gt;::epsilon() * std::fabs(x+y) * ulp\n        // unless the result is subnormal\n        || std::fabs(x-y) &lt; std::numeric_limits&lt;T&gt;::min();\n}\n\nint main()\n{\n    double d1 = 0.2;\n    double d2 = 1 / std::sqrt(5) / std::sqrt(5);\n    std::cout &lt;&lt; std::fixed &lt;&lt; std::setprecision(20) \n        &lt;&lt; "d1=" &lt;&lt; d1 &lt;&lt; "\\nd2=" &lt;&lt; d2 &lt;&lt; \'\\n\';\n\n    if(d1 == d2)\n        std::cout &lt;&lt; "d1 == d2\\n";\n    else\n        std::cout &lt;&lt; "d1 != d2\\n";\n\n    if(almost_equal(d1, d2, 2))\n        std::cout &lt;&lt; "d1 almost equals d2\\n";\n    else\n        std::cout &lt;&lt; "d1 does not almost equal d2\\n";\n}\n</code></pre>\n'}, {'answer_id': 59919755, 'author': 'Amir Saniyan', 'author_id': 309798, 'author_profile': 'https://Stackoverflow.com/users/309798', 'pm_score': -1, 'selected': False, 'text': '<p>This is another solution with lambda:</p>\n\n<pre><code>#include &lt;cmath&gt;\n#include &lt;limits&gt;\n\nauto Compare = [](float a, float b, float epsilon = std::numeric_limits&lt;float&gt;::epsilon()){ return (std::fabs(a - b) &lt;= epsilon); };\n</code></pre>\n'}, {'answer_id': 61498650, 'author': 'derke', 'author_id': 2034366, 'author_profile': 'https://Stackoverflow.com/users/2034366', 'pm_score': -1, 'selected': False, 'text': "<p>How about this?</p>\n\n<pre><code>template&lt;typename T&gt;\nbool FloatingPointEqual( T a, T b ) { return !(a &lt; b) &amp;&amp; !(b &lt; a); }\n</code></pre>\n\n<p>I've seen various approaches - but never seen this, so I'm curious to hear of any comments too!</p>\n"}, {'answer_id': 63838196, 'author': 'Oleksandr Boiko', 'author_id': 12446338, 'author_profile': 'https://Stackoverflow.com/users/12446338', 'pm_score': -1, 'selected': False, 'text': '<p>In this version you check, that numbers differ from one another not more that for some fraction (say, 0.0001%):</p>\n<pre><code>bool floatApproximatelyEquals(const float a, const float b) {\n    if (b == 0.) return a == 0.; // preventing division by zero\n    return abs(1. - a / b) &lt; 1e-6;\n}\n</code></pre>\n<p>Please note <a href="https://stackoverflow.com/users/787480/sneftel">Sneftel</a>\'s comment about possible fraction limits for float.</p>\n<p>Also note, that it differs from approach with absolute epsilons - here you don\'t bother about &quot;order of magnitude&quot; - numbers might be, say <code>1e100</code>, or <code>1e-100</code>, they will always be compared consistently, and you don\'t have to update epsilon for every case.</p>\n'}, {'answer_id': 65015333, 'author': 'Gabriel Staples', 'author_id': 4561887, 'author_profile': 'https://Stackoverflow.com/users/4561887', 'pm_score': 2, 'selected': False, 'text': '<p>You have to do this processing for floating point comparison, since float\'s can\'t be perfectly compared like integer types. Here are functions for the various comparison operators.</p>\n<h2>Floating Point Equal to (<code>==</code>)</h2>\n<p>I also prefer the subtraction technique rather than relying on <code>fabs()</code> or <code>abs()</code>, but I\'d have to speed profile it on various architectures from 64-bit PC to ATMega328 microcontroller (Arduino) to really see if it makes much of a performance difference.</p>\n<p>So, let\'s forget about all this absolute value stuff and just do some subtraction and comparison!</p>\n<p>Modified from <a href="https://learn.microsoft.com/en-us/cpp/build/why-floating-point-numbers-may-lose-precision?view=msvc-160" rel="nofollow noreferrer">Microsoft\'s example here</a>:</p>\n<pre><code>/// @brief      See if two floating point numbers are approximately equal.\n/// @param[in]  a        number 1\n/// @param[in]  b        number 2\n/// @param[in]  epsilon  A small value such that if the difference between the two numbers is\n///                      smaller than this they can safely be considered to be equal.\n/// @return     true if the two numbers are approximately equal, and false otherwise\nbool is_float_eq(float a, float b, float epsilon) {\n    return ((a - b) &lt; epsilon) &amp;&amp; ((b - a) &lt; epsilon);\n}\nbool is_double_eq(double a, double b, double epsilon) {\n    return ((a - b) &lt; epsilon) &amp;&amp; ((b - a) &lt; epsilon);\n}\n</code></pre>\n<p>Example usage:</p>\n<pre><code>constexpr float EPSILON = 0.0001; // 1e-4\nis_float_eq(1.0001, 0.99998, EPSILON);\n</code></pre>\n<p>I\'m not entirely sure, but it seems to me some of the criticisms of the epsilon-based approach, as described in the comments below <a href="https://stackoverflow.com/a/17341/4561887">this highly-upvoted answer</a>, can be resolved by using a variable epsilon, scaled according to the floating point values being compared, like this:</p>\n<pre><code>float a = 1.0001;\nfloat b = 0.99998;\nfloat epsilon = std::max(std::fabs(a), std::fabs(b)) * 1e-4;\n\nis_float_eq(a, b, epsilon);\n</code></pre>\n<p>This way, the epsilon value scales with the floating point values and is therefore never so small of a value that it becomes insignificant.</p>\n<p>For completeness, let\'s add the rest:</p>\n<h2>Greater than (<code>&gt;</code>), and less than (<code>&lt;</code>):</h2>\n<pre><code>/// @brief      See if floating point number `a` is &gt; `b`\n/// @param[in]  a        number 1\n/// @param[in]  b        number 2\n/// @param[in]  epsilon  a small value such that if `a` is &gt; `b` by this amount, `a` is considered\n///             to be definitively &gt; `b`\n/// @return     true if `a` is definitively &gt; `b`, and false otherwise\nbool is_float_gt(float a, float b, float epsilon) {\n    return a &gt; b + epsilon;\n}\nbool is_double_gt(double a, double b, double epsilon) {\n    return a &gt; b + epsilon;\n}\n\n/// @brief      See if floating point number `a` is &lt; `b`\n/// @param[in]  a        number 1\n/// @param[in]  b        number 2\n/// @param[in]  epsilon  a small value such that if `a` is &lt; `b` by this amount, `a` is considered\n///             to be definitively &lt; `b`\n/// @return     true if `a` is definitively &lt; `b`, and false otherwise\nbool is_float_lt(float a, float b, float epsilon) {\n    return a &lt; b - epsilon;\n}\nbool is_double_lt(double a, double b, double epsilon) {\n    return a &lt; b - epsilon;\n}\n</code></pre>\n<h2>Greater than or equal to (<code>&gt;=</code>), and less than or equal to (<code>&lt;=</code>)</h2>\n<pre><code>/// @brief      Returns true if `a` is definitively &gt;= `b`, and false otherwise\nbool is_float_ge(float a, float b, float epsilon) {\n    return a &gt; b - epsilon;\n}\nbool is_double_ge(double a, double b, double epsilon) {\n    return a &gt; b - epsilon;\n}\n\n/// @brief      Returns true if `a` is definitively &lt;= `b`, and false otherwise\nbool is_float_le(float a, float b, float epsilon) {\n    return a &lt; b + epsilon;\n}\nbool is_double_le(double a, double b, double epsilon) {\n    return a &lt; b + epsilon;\n}\n</code></pre>\n<h2>Additional improvements:</h2>\n<ol>\n<li>A good default value for <code>epsilon</code> in C++ is <code>std::numeric_limits&lt;T&gt;::epsilon()</code>, which evaluates to either <code>0</code> or <code>FLT_EPSILON</code>, <code>DBL_EPSILON</code>, or <code>LDBL_EPSILON</code>. See here: <a href="https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon" rel="nofollow noreferrer">https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon</a>. You can also see the <code>float.h</code> header for <code>FLT_EPSILON</code>, <code>DBL_EPSILON</code>, and <code>LDBL_EPSILON</code>.\n<ol>\n<li>See <a href="https://en.cppreference.com/w/cpp/header/cfloat" rel="nofollow noreferrer">https://en.cppreference.com/w/cpp/header/cfloat</a> and</li>\n<li><a href="https://www.cplusplus.com/reference/cfloat/" rel="nofollow noreferrer">https://www.cplusplus.com/reference/cfloat/</a></li>\n</ol>\n</li>\n<li>You could template the functions instead, to handle all floating point types: <code>float</code>, <code>double</code>, and <code>long double</code>, <em>with type checks for these types</em> via a <code>static_assert()</code> inside the template.</li>\n<li>Scaling the <code>epsilon</code> value is a good idea to ensure it works for really large and really small <code>a</code> and <code>b</code> values. This article recommends and explains it: <a href="http://realtimecollisiondetection.net/blog/?p=89" rel="nofollow noreferrer">http://realtimecollisiondetection.net/blog/?p=89</a>. So, you should scale epsilon by a scaling value equal to <code>max(1.0, abs(a), abs(b))</code>, as that article explains. Otherwise, as <code>a</code> and/or <code>b</code> increase in magnitude, the epsilon would eventually become so small relative to those values that it becomes lost in the floating point error. So, we scale it to become larger in magnitude like they are. However, using <code>1.0</code> as the smallest allowed scaling factor for epsilon also ensures that for really small-magnitude <code>a</code> and <code>b</code> values, epsilon itself doesn\'t get scaled so small that it also becomes lost in the floating point error. So, we limit the minimum scaling factor to <code>1.0</code>.</li>\n<li>If you want to &quot;encapsulate&quot; the above functions into a class, don\'t. Instead, wrap them up in a namespace if you like in order to namespace them. Ex: if you put all of the stand-alone functions into a namespace called <code>float_comparison</code>, then you could access the <code>is_eq()</code> function like this, for instance: <code>float_comparison::is_eq(1.0, 1.5);</code>.</li>\n<li>It might also be nice to add comparisons against zero, not just comparisons between two values.</li>\n<li>So, here is a better type of solution with the above improvements in place:\n<pre class="lang-cpp prettyprint-override"><code>namespace float_comparison {\n\n/// Scale the epsilon value to become large for large-magnitude a or b, \n/// but no smaller than 1.0, per the explanation above, to ensure that \n/// epsilon doesn\'t ever fall out in floating point error as a and/or b\n/// increase in magnitude.\ntemplate&lt;typename T&gt;\nstatic constexpr T scale_epsilon(T a, T b, T epsilon = \n    std::numeric_limits&lt;T&gt;::epsilon()) noexcept \n{\n    static_assert(std::is_floating_point_v&lt;T&gt;, &quot;Floating point comparisons &quot;\n        &quot;require type float, double, or long double.&quot;);\n    T scaling_factor;\n    // Special case for when a or b is infinity\n    if (std::isinf(a) || std::isinf(b)) \n    {\n        scaling_factor = 0;\n    } \n    else \n    {\n        scaling_factor = std::max({(T)1.0, std::abs(a), std::abs(b)});\n    }\n\n    T epsilon_scaled = scaling_factor * std::abs(epsilon);\n    return epsilon_scaled;\n}\n\n// Compare two values\n\n/// Equal: returns true if a is approximately == b, and false otherwise\ntemplate&lt;typename T&gt;\nstatic constexpr bool is_eq(T a, T b, T epsilon = \n    std::numeric_limits&lt;T&gt;::epsilon()) noexcept \n{\n    static_assert(std::is_floating_point_v&lt;T&gt;, &quot;Floating point comparisons &quot;\n        &quot;require type float, double, or long double.&quot;);\n    // test `a == b` first to see if both a and b are either infinity \n    // or -infinity\n    return a == b || std::abs(a - b) &lt;= scale_epsilon(a, b, epsilon);\n}\n\n/* \netc. etc.:\nis_eq()\nis_ne()\nis_lt()\nis_le()\nis_gt()\nis_ge()\n*/\n\n// Compare against zero\n\n/// Equal: returns true if a is approximately == 0, and false otherwise\ntemplate&lt;typename T&gt;\nstatic constexpr bool is_eq_zero(T a, T epsilon = \n    std::numeric_limits&lt;T&gt;::epsilon()) noexcept \n{\n    static_assert(std::is_floating_point_v&lt;T&gt;, &quot;Floating point comparisons &quot;\n        &quot;require type float, double, or long double.&quot;);\n    return is_eq(a, (T)0.0, epsilon);\n}\n\n/* \netc. etc.:\nis_eq_zero()\nis_ne_zero()\nis_lt_zero()\nis_le_zero()\nis_gt_zero()\nis_ge_zero()\n*/\n\n} // namespace float_comparison\n</code></pre>\n</li>\n</ol>\n<h2>See also:</h2>\n<ol>\n<li>The macro forms of some of the functions above in my repo here: <a href="https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world/blob/master/c/utilities.h" rel="nofollow noreferrer">utilities.h</a>.\n<ol>\n<li>UPDATE 29 NOV 2020: it\'s a work-in-progress, and I\'m going to make it a separate answer when ready, but I\'ve produced a better, scaled-epsilon version of all of the functions in C in this file here: <a href="https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world/blob/master/c/utilities.c" rel="nofollow noreferrer">utilities.c</a>. Take a look.</li>\n</ol>\n</li>\n<li><strong>ADDITIONAL READING</strong> I <s>need to do</s> now have done: <a href="http://realtimecollisiondetection.net/blog/?p=89" rel="nofollow noreferrer">Floating-point tolerances revisited, by Christer Ericson</a>. VERY USEFUL ARTICLE! It talks about scaling epsilon in order to ensure it never falls out in floating point error, even for really large-magnitude <code>a</code> and/or <code>b</code> values!</li>\n</ol>\n'}, {'answer_id': 71252885, 'author': 'Carlo Wood', 'author_id': 1487069, 'author_profile': 'https://Stackoverflow.com/users/1487069', 'pm_score': 0, 'selected': False, 'text': '<p>I use this code. Unlike the above answers this allows one to\ngive a <code>abs_relative_error</code> that is explained in the comments of the code.</p>\n<p>The first version compares complex numbers, so that the error\ncan be explained in terms of the angle between two &quot;vectors&quot;\nof the same length in the complex plane (which gives a little\ninsight). Then from there the correct formula for two real\nnumbers follows.</p>\n<p><a href="https://github.com/CarloWood/ai-utils/blob/master/almost_equal.h" rel="nofollow noreferrer">https://github.com/CarloWood/ai-utils/blob/master/almost_equal.h</a></p>\n<p>The latter then is</p>\n<pre><code>template&lt;class T&gt;\ntypename std::enable_if&lt;std::is_floating_point&lt;T&gt;::value, bool&gt;::type\n   almost_equal(T x, T y, T const abs_relative_error)\n{\n  return 2 * std::abs(x - y) &lt;= abs_relative_error * std::abs(x + y);\n}\n</code></pre>\n<p>where <code>abs_relative_error</code> is basically (twice) the absolute value of what comes closest to being defined in the literature: a relative error. But that is just the choice of the name.</p>\n<p>What it really is seen most clearly in the complex plane I think. If |x| = 1, and y lays in a circle around x with diameter <code>abs_relative_error</code>, then the two are considered equal.</p>\n'}, {'answer_id': 73599902, 'author': 'Athanasios Salamanis', 'author_id': 8794361, 'author_profile': 'https://Stackoverflow.com/users/8794361', 'pm_score': 0, 'selected': False, 'text': '<p>I use the following function for floating-point numbers comparison:</p>\n<pre><code>bool approximatelyEqual(double a, double b)\n{\n  return fabs(a - b) &lt;= ((fabs(a) &lt; fabs(b) ? fabs(b) : fabs(a)) * std::numeric_limits&lt;double&gt;::epsilon());\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/17333', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2057/']