c++ - C++ 中不同的 NaN 值

标签 c++ c++14

我原以为在 Java 和 C# 中只有一个 NaN 值,但我发现在 C++ 中有一些不同类型的 NaN 值。它们的含义相同吗?它们有什么区别:

cout << numeric_limits<double>::infinity() - numeric_limits<double>::infinity() << endl; // -nan(ind)
cout << numeric_limits<double>::quiet_NaN() << endl;//nan
if ((numeric_limits<double>::infinity() - numeric_limits<double>::infinity()) == numeric_limits<double>::quiet_NaN()) {
        cout << "THE SAME" << endl;
} 
else {
    cout << "NOT THE SAME"<<endl;
}

它打印出 NOT THE SAME,但是当我使用 std::isnan() 来测试值是否为 NaN 时两者都是正确的。

isnan(numeric_limits<double>::infinity() - numeric_limits<double>::infinity());// true
isnan(numeric_limits<double>::quiet_NaN()); // true

最佳答案

维基百科解释什么是南和安静的南:https://en.wikipedia.org/wiki/NaN

这些概念是用 C++ 实现的:

引自 https://en.cppreference.com/w/cpp/numeric/math/isnan :

There are many different NaN values with different sign bits and payloads, see std::nan and std::numeric_limits::quiet_NaN.

NaN values never compare equal to themselves or to other NaN values. Copying a NaN is not required, by IEEE-754, to preserve its bit representation (sign and payload), though most implementation do.

Another way to test if a floating-point value is NaN is to compare it with itself: bool is_nan(double x) { return x != x; }

重要的是要注意 IEEE754(表示 float 的最常用方法)没有定义一个 NaN,而是定义一种表示 NaN 的格式(这意味着几个数字可以是 NaN)。请参阅:https://en.wikipedia.org/wiki/IEEE_754-1985#NaN

All NaNs in IEEE 754-1985 have this format:

  • sign = either 0 or 1.
  • biased exponent = all 1 bits.
  • fraction = anything except all 0 bits (since all 0 bits represents infinity).

关于c++ - C++ 中不同的 NaN 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58929372/

相关文章:

c++ - Lua C API : Handling and storing additional arguments

c++ - 如果是左值则引用,如果是右值则复制一份,即使右值持久化

c++ - OpenCV 3.4.3 中对 `cv::String::deallocate()' 错误的 undefined reference

c++ - 使用 "no match"和 "cannot bind lvalue"重载 `operator<<` 时出现 `std::wostream` 和 `std::string` 错误

c++ - 在双向链表中使用智能指针

C++字符串实现错误

c++ - 在 C 和 C++ 中都有效的代码在用每种语言编译时是否会产生不同的行为?

c++ - 三个 std::complex 特化和 noexcept

c++ - 从 constexpr 干净地报告编译时错误而没有异常?

c++ - 在C++14模式下用clang for libstdc++编译regex程序报错