gpt4 book ai didi

c++ - g++ 和 clang++ 之间的浮点运算有所不同吗?

转载 作者:行者123 更新时间:2023-11-30 01:04:44 24 4
gpt4 key购买 nike

我遇到了一个似乎与平台相关的错误。对于 clang++ 和 g++,我得到了不同的结果,但仅在我的 32-Debian 机器上。我一直认为 IEEE 754 是标准化的,所有遵守该标准的编译器都会有相同的行为。如果我错了,请告诉我,我对此感到非常困惑。另外,我意识到依赖浮点比较通常不是一个好主意。

#define DEBUG(line) std::cout <<"\t\t" << #line << " => " << line << "\n";
#include <iostream>
int main() {
double x = 128.0, y = 255.0;
std::cout << "\n";
DEBUG( x/y)
DEBUG( ((x/y) == 128.0/255.0))
DEBUG( (128.0/255.0) )
DEBUG( ((x/y)-(x/y)))
DEBUG( ((x/y)-(128.0/255.0)) )
DEBUG( ((128.0/255.0)-0.501961) )
std::cout << "\n";
return 0;
}

这是我的输出

[~/Desktop/tests]$ g++ float_compare.cc -o fc
[~/Desktop/tests]$./fc

x/y => 0.501961
((x/y) == 128.0/255.0) => 0
(128.0/255.0) => 0.501961
((x/y)-(x/y)) => 0
((x/y)-(128.0/255.0)) => 6.9931e-18
((128.0/255.0)-0.501961) => -2.15686e-07

[~/Desktop/tests]$clang++ float_compare.cc -o fc
[~/Desktop/tests]$./fc

x/y => 0.501961
((x/y) == 128.0/255.0) => 1
(128.0/255.0) => 0.501961
((x/y)-(x/y)) => 0
((x/y)-(128.0/255.0)) => 0
((128.0/255.0)-0.501961) => -2.15686e-07

最佳答案

该标准允许中间结果使用扩展精度,即使在完全合规模式下也是如此(许多编译器默认情况下并不处于这种模式)。它在 [basic.fundamental] 中说:

This International Standard imposes no requirements on the accuracy of floating-point operations

对于比较 g++ 和 clang 的特定情况,请参阅 https://gcc.gnu.org/wiki/FloatingPointMath

Without any explicit options, GCC assumes round to nearest or even and does not care about signalling NaNs.

还有

For legacy x86 processors without SSE2 support, and for m68080 processors, GCC is only able to fully comply with IEEE 754 semantics for the IEEE double extended (long double) type. Operations on IEEE double precision and IEEE single precision values are performed using double extended precision. In order to have these operations rounded correctly, GCC would have to save the FPU control and status words, enable rounding to 24 or 53 mantissa bits and then restore the FPU state. This would be far too expensive.

由于 SSE(64 位)和 x87(80 位)之间的扩展精度不同,因此编译时计算的结果可能不仅取决于编译器及其版本,还取决于编译器构建时使用的标志.

您知道 IEEE 754 规则无效的方法是检查 numeric_limits<T>::is_iec559 .

关于c++ - g++ 和 clang++ 之间的浮点运算有所不同吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49471943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com