how to allocate arrays in numba

Viewed 25

I am trying to create an array inside numba jit function. I tried these two options and both return various errors

@njit
def monte_carlo_ou(T: int, nsamples: int = 100, dt:float=0.1, sigma_g:float =1.0, ):

    particles = np.zeros(T, nsamples, dtype=float)
    velocity_particles = np.zeros(nsamples , dtype=float)
    
    return particles

monte_carlo_ou(100, 50, dt=0.1, sigma_g=1.0,)

TypingError: Cannot determine Numba type of <class 'numba.core.ir.UndefinedType'>

@njit
def monte_carlo_ou(T: int, nsamples: int = 100, dt:float=0.1, sigma_g:float =1.0, ):

    particles = numba.float32[:, :]
    velocity_particles = numba.float32[:]
    
    return particles


monte_carlo_ou(100, 50, dt=0.1, sigma_g=1.0,)

Error :

TypingError: No implementation of function Function(<built-in function getitem>) found for signature:
 
getitem(class(float32), UniTuple(slice<a:b> x 2))
 
There are 22 candidate implementations:
      - Of which 22 did not match due to:
      Overload of function 'getitem': File: <numerous>: Line N/A.
        With argument(s): '(class(float32), UniTuple(slice<a:b> x 2))':
       No match.

During: typing of intrinsic-call at /var/folders/43/m_k444pn2z7c6ygxj0y3_c4r0000gn/T/ipykernel_58943/4011707724.py (6)
During: typing of static-get-item at /var/folders/43/m_k444pn2z7c6ygxj0y3_c4r0000gn/T/ipykernel_58943/4011707724.py (6)

Any advise on how to get started? All tutorials seems to be very limited

1 Answers

The problem is your first in-function line: the shape in np.zeros should be one tuple argument, not multiple scalar arguments.

particles = np.zeros(shape=(T, nsamples), dtype=float) worked for me.

shape= is not necessary but is explicit about how you should provide the shape of the array.

Related