-2

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.

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
Elliot Gorokhovsky
  • 3,610
  • 2
  • 31
  • 56
  • 1
    C has `fpclassify()` since C99. It will allow you to check for exceptional floating point values (NaNs, infinities, and subnormals), which is what you need in order to implement a function providing the behavior you describe. – John Bollinger Jul 05 '16 at 20:25

2 Answers2

2

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;
  }
}
Elliot Gorokhovsky
  • 3,610
  • 2
  • 31
  • 56
1

Try this:

#include <math.h>

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

If infinity is to be treated specially, you could also use isinf(num) as a condition and return a 'big' number of your choice.

alter_igel
  • 6,899
  • 3
  • 21
  • 40