How to compare two NAN values in C++

╄→гoц情女王★ 提交于 2019-12-08 15:27:06

问题


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?


回答1:


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)) {
  // ...
}

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) {
  // ...
}

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 provides a _isnan function.

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.




回答2:


Regarding pre-C++11, there's a boost for that, too.

#include <boost/math/special_functions/fpclassify.hpp>

template <class T>
bool isnan(T t); // NaN.



回答3:


Any given NaN is not equal to anything, it will never be equal to any other NaN, so comparing them against each other is a futile exercise.

From GNU docs:

NaN is unordered: it is not equal to, greater than, or less than anything, including itself. x == x is false if the value of x is NaN. source



来源:https://stackoverflow.com/questions/15268864/how-to-compare-two-nan-values-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!