【问题标题】:c++ test whether double is #INFc ++测试double是否为#INF
【发布时间】:2012-04-24 14:58:34
【问题描述】:

当某些double 值为NaN#INF 时,我想隔离该行为。为了检测NaN,我测试了

doubleVal != doubleVal

#INF 呢?当doubleVal#INF 时,这个测试是否成立?

【问题讨论】:

    标签: c++ double nan


    【解决方案1】:

    如果您不使用 c++11,那么您将需要 <boost/math/special_functions/fpclassify.hpp> 而不是 <cmath>,并进行相应的命名空间更改。

    #include <cmath> // or <boost/math/special_functions/fpclassify.hpp>
    // ...
    
        if(isinf(num)){
            // ...
        }
    

    【讨论】:

    • 另外,你可能应该使用std::isnan 来检查 NaN,如果只是因为它更明确的话。
    【解决方案2】:

    如果确定不是NaN,那么乘以1. 怎么样?

    http://ideone.com/97FNu

    您也可以使用isinfisnan,但根据它们的实现,它们可能会产生一些开销。

    第三种选择是使用 C 最大值宏(或等效的 std::numeric_limits):

     bool is_inf_or_nan(double x) 
    {
        return !(x <= DBL_MAX && x >= -DBL_MAX); 
    }    
    

    【讨论】:

    • 我喜欢这个替代解决方案
    【解决方案3】:

    Boost 中还有一个header-only library,它拥有处理浮点数据类型的简洁工具

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

    您将获得以下功能:

    template <class T> bool isfinite(T z);
    template <class T> bool isinf(T t);
    template <class T> bool isnan(T t);
    template <class T> bool isnormal(T t);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-29
      • 2012-07-09
      • 1970-01-01
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多