Checking for nan in Cython

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

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

Tags:

Python

Cython