Ad

While Loop Strange And Unstable Behavior In A Jitted Function

- 1 answer

I found that when the index of a numpy array will go out of bound inside a while-loop in a njit decorated function, the way the function handles the while loop can quite weird, and I am not sure why it happens.

from numba import njit
import numpy as np


def func1(v):
    i= 0
    K= v[-1]+1
    while v[i] < K:
        i+=1
    return i

@njit        
def func2(v):
    i= 0
    K= v[-1]+1
    while v[i] < K:
        i+=1
    return i

x= np.arange(2)
result2 = func2(x)
result1 = func1(x)

Here is a short summary of the results:

1) func2 won't raise IndexError

2) func2 returns different results(like sometimes it is 4; sometimes 5,9,12, etc, basically unstable output) every time we run the file in the console (I am using ipython version 7.8.0)

I am not sure why and how this happens(could be due to numba or spyder or ipython issues or it could be that my cpu is broken beyond repair) which is why I am asking for help here.


Note: I am using:

  • Anaconda's distribution of python, python version 3.7.4,

  • spyder version 3.3.6,

  • ipython version 7.8.0,

  • numba version 0.45.1

  • OS windows 10 64-bit

Ad

Answer

Numba does not do bounds checking on Numpy arrays for performance reasons. There is currently work to turn it on optionally (https://github.com/numba/numba/pull/4432). When you go outside of the bounds of the array you will get whatever is in memory at the location or possibly seg fault.

Ad
source: stackoverflow.com
Ad