c++cnumerical

Equivalent of numpy.nan_to_num in C/C++


How can I achieve behavior equivalent to numpy's numpy.nan_to_num function in C/C++?

Specificiation for non-python programmers:

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.


Solution

  • I ended up using this, since I want to maintain continuity. It works with opencl as well, and doesn't require any C99 stuff.

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