C++ std::isnan及std::isinf

C++ std::isnan及std::isinf

std::isnan及std::isinf

摘自isnanisnan函數的簽名為:

bool isnan (float x);
bool isnan (double x);
bool isnan (long double x);

它的作用為:

Returns whether x is a NaN (Not-A-Number) value.

The NaN values are used to identify undefined or non-representable 
values for floating-point elements, such as the square root of 
negative numbers or the result of 0/0.

即用來判斷一個浮點數是否為未定義或無法表示的值,如負數的根號值,負數的log值或0/0。

要注意的是1.0/0.0或-1.0/0.0並不是NaN,而是Inf(無限)。如果要判斷一個浮點數是否為無限,則應該使用std::isinf這個函數。

筆者寫了一段代碼:cpp-code-snippets/isnan_isinf.cpp,用來測試這兩個函數,以下為其運行結果:

0.0/0.0    is nan? 1, is inf? 0
sqrt(-1.0) is nan? 1, is inf? 0
log(-1.0)  is nan? 1, is inf? 0
1.0/0.0    is nan? 0, is inf? 1
-1.0/0.0   is nan? 0, is inf? 1

TensorRT/parsers/caffe/caffeWeightFactory/caffeWeightFactory.cpp的函數CaffeWeightFactory::checkForNans中:

template <typename T>
bool CaffeWeightFactory::checkForNans(const void* values, int count, const std::string& layerName)
{
    const T* v = reinterpret_cast<const T*>(values);
    for (int i = 0; i < count; i++)
    {
        if (std::isnan(float(v[i])))
        {
            //...
            return false;
        }
    }
    return true;
}

便用std::isnan函數來判斷float(v[i])是否為NaN。

參考連結

isnan

isinf

cpp-code-snippets/isnan_isinf.cpp

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值