Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for nan in Cython

Tags:

python

cython

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?

like image 545
astrofrog Avatar asked Nov 20 '11 08:11

astrofrog


People also ask

How can I check for nan values?

The math. isnan() method checks whether a value is NaN (Not a Number), or not. This method returns True if the specified value is a NaN, otherwise it returns False.

How do you check if a float is a nan?

To check whether a floating point or double number is NaN (Not a Number) in C++, we can use the isnan() function. The isnan() function is present into the cmath library. This function is introduced in C++ version 11.

How do you check if a value is 1 nan in Python?

To check if value at a specific location in Pandas is NaN or not, call numpy. isnan() function with the value passed as argument. If value equals numpy. nan, the expression returns True, else it returns False.

How do I get nan in Python?

nan is a float value in Python In Python, the float type has nan . You can create nan with float('nan') . Other creation methods are described later. For example, if you read a CSV file in NumPy or pandas, the missing values are represented by nan ( NaN in pandas).


2 Answers

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
like image 86
Chris Morgan Avatar answered Oct 18 '22 19:10

Chris Morgan


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
like image 35
cpaulik Avatar answered Oct 18 '22 19:10

cpaulik