user599395
user599395

Reputation: 11

Numpy matrix functions with Numba

I am new to Python programming. I have the following Python 3.6 code:

import numpy as np
from numba import jit
@jit(nopython=True)
def genarray(rows, cols):
    """return a new matrix"""
    return np.zeros([rows, cols], float)
L1 = 5
C1 = 5
B = genarray(L1, C1)
print(type(B))

When I compile I obtain the following error:

TypingError: >Invalid usage of Function(<built-in function zeros>) with parameters (list(int64), Function(<class 'float'>))

 * parameterized

I tried with np.float, np.float64 and I obtain errors. The code compiles OK without the nopython=true option.

How solve the error with the matrices? Because with vector the code compiles OK with nopython=true option.

Upvotes: 0

Views: 1214

Answers (1)

DSM
DSM

Reputation: 353099

I second the concern that worrying about numba at this point may not be the most productive path. That said, you can achieve your goal by passing a tuple and not a list to np.zeros and using np.float64:

>>> @jit(nopython=True)
... def genarray(rows, cols):
...     """return a new matrix"""
...     return np.zeros((rows, cols), np.float64)
... 
>>> L1 = 5
>>> C1 = 5
>>> B = genarray(L1, C1)
>>> print(type(B))
<class 'numpy.ndarray'>
>>> B
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])

If this seems pretty finicky, you're right: but that's the tradeoff with using numba at the moment.

Upvotes: 3

Related Questions