3

I compiled a Cython script and run it. When running it I got an error from the following line of code:

cdef np.ndarray[float] vola = np.empty(n, dtype=float)

Why is that? I want to fill the array vola with float values later on, so I want to format it as float, not double.

user3276418
  • 1,777
  • 4
  • 20
  • 29

1 Answers1

8

Just use cdef np.ndarray[double] vola = np.empty(n, dtype=float).

Example in ipython with cythonmagic (see an example here):

%%cython
import numpy as np
cimport numpy as np
cpdef foo(n):
    cdef np.ndarray[double] vola = np.empty(n, dtype=float)
    return vola

foo(4)  #output :
array([ 2.14079666e-314, 2.14079666e-314, 2.17357252e-314, 2.78136356e-309])

This happens because a numpy float is a C double.

EDIT: for a more portable/mantainable code, you may use np.float64_t instead of double, and specify dtype=np.float64 in the call to empty().

gg349
  • 21,996
  • 5
  • 54
  • 64