c++ - 为什么使用英特尔 C++ 编译器时 NaN - NaN == 0.0?

标签 c++ c floating-point ieee-754 icc

众所周知,NaN在算术中传播,但是我找不到任何演示,所以我写了一个小测试:

#include <limits>
#include <cstdio>

int main(int argc, char* argv[]) {
    float qNaN = std::numeric_limits<float>::quiet_NaN();

    float neg = -qNaN;

    float sub1 = 6.0f - qNaN;
    float sub2 = qNaN - 6.0f;
    float sub3 = qNaN - qNaN;

    float add1 = 6.0f + qNaN;
    float add2 = qNaN + qNaN;

    float div1 = 6.0f / qNaN;
    float div2 = qNaN / 6.0f;
    float div3 = qNaN / qNaN;

    float mul1 = 6.0f * qNaN;
    float mul2 = qNaN * qNaN;

    printf(
        "neg: %f\nsub: %f %f %f\nadd: %f %f\ndiv: %f %f %f\nmul: %f %f\n",
        neg, sub1,sub2,sub3, add1,add2, div1,div2,div3, mul1,mul2
    );

    return 0;
}

这个例子(running live here)基本上产生了我所期望的(否定有点奇怪,但有点道理):

neg: -nan
sub: nan nan nan
add: nan nan
div: nan nan nan
mul: nan nan

MSVC 2015 产生了类似的东西。但是,英特尔 C++ 15 会产生:

neg: -nan(ind)
sub: nan nan 0.000000
add: nan nan
div: nan nan nan
mul: nan nan

具体来说,qNaN - qNaN == 0.0.

这……不可能吧?相关标准(ISO C、ISO C++、IEEE 754)对此有何规定,为什么编译器之间的行为存在差异?

最佳答案

英特尔 C++ 编译器中的默认浮点处理是 /fp:fast,它不安全地处理 NaN(这也会导致 NaN == NaN true 例如)。尝试指定 /fp:strict/fp:precise 看看是否有帮助。

关于c++ - 为什么使用英特尔 C++ 编译器时 NaN - NaN == 0.0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32195949/

相关文章:

从 Shell 脚本收集返回值

降低 R 中 double

c# - 了解 float 问题

c++ - 在 C 结构中定义 C++ 函数

c - 为什么 malloc 分配的内存空间比我要求的多?

c - OpenGL glutWireCube 可以工作,但 glutWireCylinder 不能。我究竟做错了什么?

shell - 如何从shell中的二进制文件打印浮点值?

c++ - 使用模板减少 const 和非 const 非成员函数的代码重复

android - 有没有等同于#ifdef WIN32 的#ifdef ANDROID

c++ - 如何修复我的指针和数组函数中 Unresolved external 错误 - LNK2019 和 LNK1120