Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a numpy array of a given type with numba

Since Numba 0.19 one is able to explicitly create numpy arrays in nopython mode. How can I create an array of a given type?

from numba import jit
import numpy as np

@jit(nopython=True)
def f():
    a = np.zeros(5, dtype = np.int)

The above code fails with the following error

TypingError: Failed at nopython (nopython frontend)
Undeclared Function(<built-in function zeros>)(int32, Function(<class 'int'>))
File "<ipython-input-4-3169be7a8201>", line 6
like image 392
gota Avatar asked Mar 16 '23 12:03

gota


2 Answers

You should use numba dtypes instead of numpy

import numba
import numpy as np

@numba.njit
def f():
    a = np.zeros(5, dtype=numba.int32)
    return a

In [8]: f()
Out[8]: array([0, 0, 0, 0, 0], dtype=int32)
like image 141
Daniel Lenz Avatar answered Mar 23 '23 16:03

Daniel Lenz


In python 2.7 it seems that np.int does work.

As for the workaround from dlenz, I'd like to point that using np.int32 does work as well... with the added advantage that the code will work without modifications if you want to remove numba.njit at some point for whatever reason.

like image 25
osvil Avatar answered Mar 23 '23 15:03

osvil