How to represent inf or -inf in Cython with numpy?

I am creating an array with a cython element by element. I would like to keep the constant np.inf (or -1 * np.inf ) in some elements. However, this will require the overhead of returning to Python to search for inf . Is there an libc.math equivalent of this constant? Or some other value that can be easily used, which is equivalent (-1*np.inf) and can be used from Cython without overhead?

EDIT example:

 cdef double value = 0 for k in xrange(...): # use -inf here -- how to avoid referring to np.inf and calling back to python? value = -1 * np.inf 
+6
source share
4 answers

There is no literal for it, but a float can parse it from a string:

 >>> float('inf') inf >>> np.inf == float('inf') True 

Alternatively, math.h can (almost certainly will) declare a macro that computes the value of inf, in which case you can simply use this:

 cdef extern from "math.h": float INFINITY 

(There is no clean way to check if INFINITY is defined in pure Cython, so if you want to span all of your databases, you will need to hack. One way to do this is to create a small C header, say fallbackinf.h :

 #ifndef INFINITY #define INFINITY 0 #endif 

And then in your .pyx file:

 cdef extern from "math.h": float INFINITY cdef extern from "fallbackinf.h": pass inf = INFINITY if INFINITY != 0 else float('inf') 

(You cannot assign INFINITY because it is an rvalue. You can end the ternary operator if #defined INFINITY is like 1.0 / 0.0 in your header, but it can raise SIGFPE, depending on your compiler.)

This is certainly in the field of optimizing the cult of the load.)

+10
source

Recommended way to do it in Cython:

 from numpy.math cimport INFINITY 

Please note that this is "cimport" and not a regular import. This is the official Cython shell around NumPy npymath .

+8
source

You can use the Numpy math library to see what is available :

  cdef extern from "numpy / npy_math.h":
     double inf "NPY_INFINITY"

When creating the Cython extension module, you need to specify the correct include directory and library for the link:

  >>> from numpy.distutils.misc_util import get_info
 >>> get_info ('npymath')
 {'define_macros': [], 
  'libraries': ['npymath', 'm'], 
  'library_dirs': ['/usr/lib/python2.7/dist-packages/numpy/core/lib'], 
  'include_dirs': ['/usr/lib/python2.7/dist-packages/numpy/core/include']}

Information obtained from this function can be passed to Python distutils or any build system used.

+3
source

There is also sys.maxint in the standard library

-1
source

All Articles