Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

checking if double values equal

http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm

Extending from the float sample, is what I have below the correct version for double?
Specifically, it's the 0x8000000000000000....not sure if this is the right value for 0 in 64bit.

Can someone check if this is correct?

bool AlmostEqual2sComplement(double A, double B, long long maxUlps)
{
// Make sure maxUlps is non-negative and small enough that the default NAN won't compare as equal to anything.
assert(maxUlps > 0 && maxUlps < 8 * 1024 * 1024);
long long aInt = *(long long*)&A;
// Make aInt lexicographically ordered as a twos-complement int
if (aInt < 0)
{
aInt = 0x8000000000000000 - aInt;
}
// Make bInt lexicographically ordered as a twos-complement int
long long bInt = *(long long*)&B;
if (bInt < 0)
{
bInt = 0x8000000000000000 - bInt;
}

long long intDiff = aInt - bInt;
if (intDiff<0)
{
intDiff *= -1;
}

if (intDiff <= maxUlps)
{
return true;
}
return false;
}
[1190 byte] By [rssmps] at [2007-11-11 10:26:34]
# 1 Re: checking if double values equal
You should consider using the <limits> library to avoid portability problems: http://www.dev-archive.com/cplus/10MinuteSolution/30891
This way you avoid NANs and check the epsilon of each platform.
Danny at 2007-11-11 20:58:46 >
# 2 Re: checking if double values equal
You should consider using the <limits> library to avoid portability problems:

Thanks! This worked better as you said. I did encounter issues with portability with the other method.
rssmps at 2007-11-11 20:59:51 >