我试图避免使用 epsilon 比较来比较浮点类型。我能想出的最佳解决方案使用了 ULP 的差异(最后的单位),尽管本文使用整数表示有一个更好的解决方案(请///
指出我自己的评论):
/* 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;
}
但是,我似乎无法以支持双打的方式重新格式化代码。我什至阅读了这里的解释。
有谁知道解决这个问题的最佳方法是什么?
在任何人决定将此标记为重复之前:不要,因为唯一类似的问题是针对 javascript 的,而 C++ 的答案是:
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);
}
它不使用 ULP,而是某种绑定,我不确定是什么-9223372036854775808LL - aInt
(也许 int64 溢出的地方)。