如果我将浮点数复制到另一个变量,它们是否相等? [英] If I copy a float to another variable, will they be equal?
问题描述
我知道使用==
检查浮点变量的相等性不是一个好方法.但是我只想通过以下语句知道这一点:
float x = ...
float y = x;
assert(y == x)
由于从x
复制了y
,所以断言为真吗?
除了kmdreko指出的assert(NaN==NaN);
情况外,您还可能遇到x87-math的情况,即将80位浮点数临时存储到内存中,然后与值进行比较仍然存储在寄存器中.
可能的最小示例,当使用-O2 -m32
编译时,它在gcc9.2上失败:
#include <cassert>
int main(int argc, char**){
float x = 1.f/(argc+2);
volatile float y = x;
assert(x==y);
}
Godbolt演示: https://godbolt.org/z/X-Xt4R >
如果您设法创建足够的寄存器压力来存储y
并从内存中重新加载,则可以省略volatile
(但要使编译器感到困惑,不要完全省略比较).
请参阅GCC常见问题解答参考:
I know that using ==
to check equality of floating-point variables is not a good way. But I just want to know that with the following statements:
float x = ...
float y = x;
assert(y == x)
Since y
is copied from x
, will the assertion be true?
Besides the assert(NaN==NaN);
case pointed out by kmdreko, you can have situations with x87-math, when 80bit floats are temporarily stored to memory and later compared to values which are still stored inside a register.
Possible minimal example, which fails with gcc9.2 when compiled with -O2 -m32
:
#include <cassert>
int main(int argc, char**){
float x = 1.f/(argc+2);
volatile float y = x;
assert(x==y);
}
Godbolt Demo: https://godbolt.org/z/X-Xt4R
The volatile
can probably be omitted, if you manage to create sufficient register-pressure to have y
stored and reloaded from memory (but confuse the compiler enough, not to omit the comparison all-together).
See GCC FAQ reference:
这篇关于如果我将浮点数复制到另一个变量,它们是否相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!