Checking for nan in Cython

2019-04-19 05:34发布

I'm looking for a way to check for NaN values in Cython code. At the moment, I'm using:

if value != value:
    # value is NaN
else:
    # value is not NaN

Is there a better way to do this? Is it possible to use a function like Numpy's isnan?

标签: python cython
2条回答
叛逆
2楼-- · 2019-04-19 05:47

Taken from http://groups.google.com/group/cython-users/msg/1315dd0606389416, you could do this:

cdef extern from "math.h":
    bint isnan(double x)

Then you can just use isnan(value).

In newer versions of Cython, it is even easier:

from libc.math cimport isnan
查看更多
闹够了就滚
3楼-- · 2019-04-19 05:48

If you want to make sure that your code also works on Windows you should better use

cdef extern from "numpy/npy_math.h":
    bint npy_isnan(double x)

because on Windows, as far as I know, isnan is called _isnan and is defined in float.h

See also here for example: https://github.com/astropy/astropy/pull/186

If you don't want to introduce numpy you could also insert these precompiler directives into the .c file cython generates:

#if defined(WIN32) || defined(MS_WINDOWS)
#define USEMATH_DEFINES
#define isnan(x) _isnan(x)
#endif
查看更多
登录 后发表回答