I have tried to avoid epsilon comparisons for comparing floating point types. The best solution I could come up with used the difference in ULPs (Unit in the last place), though this article had a much better solution using integer representations (///
indicate my own comments):
/* See
https://randomascii.wordpress.com/2012/01/11/tricks-with-the-floating-point-format/
for the potential portability problems with the union and bit-fields below.
*/
#include <stdint.h> // For int32_t, etc.
union Float_t
{
Float_t(float num = 0.0f) : f(num) {}
// Portable extraction of components.
bool Negative() const { return i < 0; }
int32_t RawMantissa() const { return i & ((1 << 23) - 1); }
int32_t RawExponent() const { return (i >> 23) & 0xFF; }
int32_t i; /// Perhaps overflow when using doubles?
float f;
#ifdef _DEBUG
struct
{ // Bitfields for exploration. Do not use in production code.
uint32_t mantissa : 23; /// 52 for double?
uint32_t exponent : 8; /// 11 for double?
uint32_t sign : 1;
} parts;
#endif
};
bool AlmostEqualUlps(float A, float B, int maxUlpsDiff)
{
Float_t uA(A);
Float_t uB(B);
// Different signs means they do not match.
if (uA.Negative() != uB.Negative())
{
// Check for equality to make sure +0==-0
if (A == B)
return true;
return false;
}
// Find the difference in ULPs.
int ulpsDiff = abs(uA.i - uB.i);
if (ulpsDiff <= maxUlpsDiff)
return true;
return false;
}
However, I can't seem to reformat the code in such a way that it supports doubles. I even read up on the explanation, found here.
Does anyone know what would be the best way to tackle this?
Before anyone decides to mark this as a duplicate: don't, because the only question that was similar was meant for javascript, and the C++ answer was:
bool IsAlmostEqual(double A, double B)
{
//http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
long long aInt = reinterpret_cast<long long&>(A);
if (aInt < 0) aInt = -9223372036854775808LL - aInt;
long long bInt = reinterpret_cast<long long&>(B);
if (bInt < 0) bInt = -9223372036854775808LL - bInt;
return (std::abs(aInt - bInt) <= 10000);
}
Which doesn't use ULPs, but some kind of bound, and I'm not sure what -9223372036854775808LL - aInt
is at all (perhaps where int64 overflows).