g++ 和 clang++ 之间的浮点运算不同?

Floating point arithmetic varies between g++ and clang++?

我遇到了一个似乎与平台相关的错误。我在 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 位)的扩展精度不同,compile-time 计算的结果可能不仅取决于编译器及其版本,还取决于标记编译器是用.

构建的

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