如何比较C ++中的两个NAN值 [英] How to compare two NAN values in C++

查看:220
本文介绍了如何比较C ++中的两个NAN值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,其中代码区产生NAN值。我必须比较相等的值,并基于执行其余的代码。如何比较两个NAN值在C ++中的相等?

解决方案

假设使用IEEE 754浮点表示法,您不能比较两个NaN值的相等性。 NaN不等于任何值,包括自身。不过,您可以使用 std :: isnan 测试他们是否都是NaN $ c> $ c>

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

但是,这仅在C ++ 11中可用。在C ++ 11之前, Boost数学工具包提供一些浮点分类 。或者,您可以通过与自身比较来检查值是否为NaN:

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

NaN是唯一不等于自身的值。在过去,某些编译器搞砸了,但我不知道当前的状态(它似乎与GCC正常工作)。



MSVC提供了一个 _isnan 功能。



最后替代是假设你知道表示是IEEE 754并做一些位检查。显然这不是最便携的选择。


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?

解决方案

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.

这篇关于如何比较C ++中的两个NAN值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆