C++ AlmostQual2SComplete实现不处理退化案例
我实现了由提出的AlmostQual2SComplete,但用于比较double而不是float值 类似的实现可以在许多地方找到C++ AlmostQual2SComplete实现不处理退化案例,c++,floating-point,comparison,C++,Floating Point,Comparison,我实现了由提出的AlmostQual2SComplete,但用于比较double而不是float值 类似的实现可以在许多地方找到 bool AlmostEqual2sComplement(double A, double B, int maxUlps= 10) { // Make sure maxUlps is non-negative and small enough that the // default NAN won't compare as equal to anyth
bool AlmostEqual2sComplement(double A, double B, int maxUlps= 10)
{
// 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;
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= intDiff*-1;
if (intDiff <= maxUlps)
return true;
return false;
}
intDiff导致0x80000000000000
的情况肯定更多(可能不是很明显)
我想知道AlmosteQual2sComplete的其他实现是否没有意识到这个问题,或者我在最初的实现中是否犯了错误?这是更正的版本,其中有一个额外的检查,检查两个浮点数是否有相反的符号。这是更正的版本,如果需要额外检查两个浮点数是否有相反的符号。谢谢,太好了。这就解决了问题!因为如果符号aInt和bInt相等,intDiff永远不会产生下溢。谢谢,太好了。这就解决了问题!因为如果符号aInt和bInt相等,intDiff永远不会产生下溢。
if (intDiff <= maxUlps && -maxUlps <= intDiff)
return true;