C++ std::isnan及std::isinf
std::isnan及std::isinf
摘自isnan,isnan
函數的簽名為:
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。