Cython: assigning INFINITY or numpy.inf to a typed variable results to 0

340 views Asked by At

I wish to cdef an INFINITY constant in a file named constant.pxd so that I can cimport it elsewhere. Assume in constant.pxd we have:

import numpy as np
cimport numpy as np
from libc cimport math

ctypedef np.float32_t dtype_t

cdef dtype_t INF = math.INFINITY if math.INFINITY != 0. else np.float32('inf')

This, however, does not work, as for example, in another .pyx file:

from constant cimport INF
cpdef test():
    return INF

Which yields:

>> 0.0

I also tried to define INF directly as np.float32('inf') or np.inf. However, they all end up with being zeros.

I can, however, define INF = np.float32('inf') without typing it, in a .pyx file, say constant.pyx and use it as expected. I am not clear whether this might result in performing issues, if we have, say:

from constant import INF
from constant cimport dtype_t

cdef class A:
    cdef dtype_t data

    def __cinit__(self, dtype_t data):
          self.data = data
# ...

And with:

from constant import INF

a = A(INF)
0

There are 0 answers