我有一个简单的程序,使用numba添加两个数组:

import numpy
import numba

@numba.jit(
    numba.void(numba.float64[:], numba.float64[:], numba.float64[:]),
    nopython=True)
def add(c, a, b):
    c[:] = a[:] + b[:]

if __name__ == '__main__':
    a = numpy.arange(10000) * 1.0
    b = numpy.arange(10000) * 1.0
    c = numpy.zeros_like(a)
    add(c, a, b)
    print(c)


当我尝试运行它时,我从JIT编译器收到以下错误:

numba.typeinfer.TypingError: Failed at nopython (nopython frontend)
Undeclared +(array(float64, 1d, A), array(float64, 1d, A))


有没有办法使它起作用,还是应该改用guvectorize()

最佳答案

我建议检查您的numba版本,从0.19.1开始,有一些cool, new features用于处理数组。而且,numba不一定是可以很容易矢量化的简单操作的方式。

import numpy as np
import numba

@numba.njit
def add_numba(c, a, b):
    c = a + b
    return c

def add_no_numba(c, a, b):
    c = a + b
    return c

if __name__ == '__main__':
    print numba.__version__

    a = np.arange(10000, dtype=np.float64)
    b = np.arange(10000, dtype=np.float64)

    # numba
    c = np.zeros_like(a, dtype=np.float64)
    %timeit add_numba(c, a, b)
    print add_numba(c, a, b)

    # no numba
    c = np.zeros_like(a, dtype=np.float64)
    %timeit add_no_numba(c, a, b)
    print add_no_numba(c, a, b)

>> 0.19.1
>> 10000 loops, best of 3: 24.8 µs per loop
>> [  0.00000000e+00   2.00000000e+00  ...,    1.99980000e+04]
>> 100000 loops, best of 3: 7.44 µs per loop
>> [  0.00000000e+00   2.00000000e+00  ...,    1.99980000e+04]

关于python - numba中两个数组的未声明加法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30448018/

10-14 18:08