如何在 C++ 中比较两个 NAN 值

2022-01-25 00:00:00 nan compare c++

我有一个代码区域产生 NAN 值的应用程序.我必须比较相等的值并在此基础上执行其余代码.如何比较 C++ 中的两个 NAN 值是否相等?

I have an application in which a code area produces NAN values. I have to compare the values for equality and based on that execute the rest of the code.How to compare two NAN values in C++ for equality?

推荐答案

假设 IEEE 754 浮点表示,您无法比较两个 NaN 值是否相等.NaN 不等于任何值,包括它自己.但是,您可以使用 std::isnan 来自 <cmath> 标头:

Assuming an IEEE 754 floating point representation, you cannot compare two NaN values for equality. NaN is not equal to any value, including itself. You can however test if they are both NaN with std::isnan from the <cmath> header:

if (std::isnan(x) && std::isnan(y)) {
  // ...
}

不过,这仅在 C++11 中可用.在 C++11 之前,Boost Math Toolkit 提供了一些浮点分类器.或者,您可以通过与自身进行比较来检查值是否为 NaN:

This is only available in C++11, however. Prior to C++11, the Boost Math Toolkit provides some floating point classifiers. Alternatively, you can check if a value is NaN by comparing it with itself:

if (x != x && y != y) {
  // ...
}

因为 NaN 是唯一不等于自身的值.过去,某些编译器将其搞砸了,但我目前不确定状态(它似乎与 GCC 一起正常工作).

Since NaN is the only value that is not equal to itself. In the past, certain compilers screwed this up, but I'm not sure of the status at the moment (it appears to work correctly with GCC).

MSVC 提供了一个 _isnan 函数.

MSVC provides a _isnan function.

最后一种选择是假设您知道表示是 IEEE 754 并进行一些位检查.显然这不是最便携的选择.

The final alternative is to assume you know the representation is IEEE 754 and do some bit checking. Obviously this is not the most portable option.

相关文章