C/C++ 中 numpy.nan_to_num 的等价物

Equivalent of numpy.nan_to_num in C/C++

如何在 C/C++ 中实现与 numpy 的 numpy.nan_to_num 函数等效的行为?

非python程序员的规范:

Replace nan with zero and inf with finite numbers.

Returns an array or scalar replacing Not a Number (NaN) with zero, (positive) infinity with a very large number and negative infinity with a very small (or negative) number. ... NaN is replaced by zero, and infinity (-infinity) is replaced by the largest (smallest or most negative) floating point value that fits in the output dtype.

试试这个:

#include <math.h>

double normalize(double num)
    if (isnormal(num)){
        return num;
    } else {
        return 0;
    }
}

如果要特殊处理无穷大,您还可以使用 isinf(num) 作为条件,并使用 return 您选择的 'big' 数字。

我最终使用了这个,因为我想保持连续性。它也适用于 opencl,并且不需要任何 C99 的东西。

float nan_to_num(float num){
  if (isinf(num)){
    if (signbit(num))
      return -MAXFLOAT;
    else
      return MAXFLOAT;
  } else {
    return num;
  }
}