简体   繁体   中英

Indexing empty array, Numba vs. Numpy

I was experimenting with the behavior of Numba vs Numpy for array indexing, and I came across something which I do not quite understand; so I hoped someone can point me in the right direction for what is probably a very simple question. Below are two functions, both of which create an empty array using the np.arange command. I then "append" (experimenting with a variety of methods to see how both Numba and Numpy perform/break) to the array using an index of 0, example[0] = 1 .

The Numba function with jit runs without error, but the Numpy example gives the error:

IndexError: index 0 is out of bounds for axis 0 with size 0

The Numpy error makes sense, but I am unsure as to why Numba with jit enabled allows the operation without error.

import numba as nb
import numpy as np

@nb.jit()
def funcnumba():
    '''
    Add item to position 0 using Numba
    '''
    example = np.arange(0)
    example[0] = 1
    return example

def funcnumpy():
    '''
    Add item to position 0 using Numpy. This produces an error which makes sense
    '''
    example = np.arange(0)
    example[0] = 1
    return example

print(funcnumba())

print(funcnumpy())

See the Numba documentation on arrays :

Currently there are no bounds checking for array indexing and slicing (...)

That means that you will be writing out of the bounds of the array in this case. Since it is just one element you may be lucky and get away with it, but you can also crash your program or, even worse, silently overwrite some other value. See issue #730 for a discussion about it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM