Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy types for Cython users

I'm not quite understand what is the difference between numpy.{typename}, numpy.npy_{typename} and numpy.{typename}_t when i use them from Cython code?

i.e. what is the difference in these types:

# test.pyx
cimport numpy as np
import numpy as np

np.float32
np.npy_float32
np.float32_t

As i understand it now: first type is dynamic, i.e. Cython will generate some code to detect size of that type at runtime. Two other types are static, i.e. code which uses it will be compiled with predefined sizes of each type. Please correct me.

Additional link: https://docs.scipy.org/doc/numpy/reference/c-api.dtype.html#c-type-names

like image 612
Ibraim Ganiev Avatar asked Jan 04 '16 18:01

Ibraim Ganiev


People also ask

Can I use NumPy in Cython?

You can use NumPy from Cython exactly the same as in regular Python, but by doing so you are losing potentially high speedups because Cython has support for fast access to NumPy arrays.

Does Cython improve NumPy?

By explicitly declaring the "ndarray" data type, your array processing can be 1250x faster. This tutorial will show you how to speed up the processing of NumPy arrays using Cython. By explicitly specifying the data types of variables in Python, Cython can give drastic speed increases at runtime.

Does SciPy use Cython?

All files with a . pyx extension are automatically converted by Cython to . c files when SciPy is built.


1 Answers

np.float32 is NumPy's TypeDescriptor, which is a Python object which can be queried and passed to NumPy to construct arrays just as in Python.

np.npy_float32 is a C type, which can be used wherever a C type is needed, e.g.

cdef np.npy_float32 x = 1.902
cdef np.ndarray[np.npy_float32, ndim=2] A = np.zeros((3, 4), dtype=np.float32)

np.float32_t is simply a typedef of np.npy_float32 which can be used as a shorthand.

like image 76
robertwb Avatar answered Sep 29 '22 00:09

robertwb