N
nw
Hi,
I'd like to compare 2 floating point numbers within a given error. I'd
rather not use a absolute error but one related to the number of
values that can be represented between the two floats. I've been
reading: http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
where the following function is provided to do this:
bool AlmostEqual2sComplement(float A, float B, int 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 < 4 * 1024 * 1024);
int aInt = *(int*)&A;
// Make aInt lexicographically ordered as a twos-complement int
if (aInt < 0)
aInt = 0x80000000 - aInt;
// Make bInt lexicographically ordered as a twos-complement int
int bInt = *(int*)&B;
if (bInt < 0)
bInt = 0x80000000 - bInt;
int intDiff = abs(aInt - bInt);
if (intDiff <= maxUlps)
return true;
return false;
}
However, as the article states, this relies on a number of compiler
specific features, such as the size of int (and I guess float). It
also relies on the floats using IEEE representation (I guess all
compilers use this, but is it in the standard?).
So my question is this. Is there a good compiler independent method
for comparing floating point numbers with a relative error?
I'd like to compare 2 floating point numbers within a given error. I'd
rather not use a absolute error but one related to the number of
values that can be represented between the two floats. I've been
reading: http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
where the following function is provided to do this:
bool AlmostEqual2sComplement(float A, float B, int 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 < 4 * 1024 * 1024);
int aInt = *(int*)&A;
// Make aInt lexicographically ordered as a twos-complement int
if (aInt < 0)
aInt = 0x80000000 - aInt;
// Make bInt lexicographically ordered as a twos-complement int
int bInt = *(int*)&B;
if (bInt < 0)
bInt = 0x80000000 - bInt;
int intDiff = abs(aInt - bInt);
if (intDiff <= maxUlps)
return true;
return false;
}
However, as the article states, this relies on a number of compiler
specific features, such as the size of int (and I guess float). It
also relies on the floats using IEEE representation (I guess all
compilers use this, but is it in the standard?).
So my question is this. Is there a good compiler independent method
for comparing floating point numbers with a relative error?