我们可以依靠op ==二进制比较浮点值吗? [英] Can we rely on op== to binary-compare floating-point values?
问题描述
我们都知道(对吗?!)不应该通过测试等于( operator ==
)来比较浮点值。
但是如果我真的想确定两个 float
s a
和 b
是二进制平等?如果他们不被允许是NaN(或其他特殊价值),这是安全的?我可以依靠运算符==
以这种方式运行吗?
(假设IEEE-754表示)差不多,但不完全。如果你可以排除NaN,你仍然需要处理 +0.0
和 -0.0
具有不同的二进制编码,但比较相等(因为两者都完全为零)。当然,C ++不需要IEEE-754。所以,严格来说,所有的赌注都是关闭的。
如果您想检查编码是否相等,只需使用 memcmp(& a ,& b,sizeof a)
。
We all know (right?!) that one should not compare floating-point values by testing for equality (operator==
).
But what if I actually want to determine whether two float
s a
and b
are binary equal? If they're not allowed to be NaN (or other "special values"), is this "safe"? Can I rely on operator==
to function in this way?
(Assuming IEEE-754 representations) almost, but not quite. If you can rule out NaNs, you still need to deal with the fact that +0.0
and -0.0
have different binary encodings, but compare equal (because both are exactly zero).
Of course, C++ doesn't require IEEE-754. So strictly speaking, all bets are off.
If you want to check for (in)equality of encoding, just use memcmp(&a, &b, sizeof a)
.
这篇关于我们可以依靠op ==二进制比较浮点值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!