我原以为在 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/types/numeric_limits/quiet_NaN
- https://en.cppreference.com/w/cpp/numeric/math/nan
引自 https://en.cppreference.com/w/cpp/numeric/math/isnan :
There are many different NaN values with different sign bits and payloads, see
std::nan
andstd::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/