I'm trying to learn Python and Numba and I can't figure out why the following code doesn't compute in IPython/Jupyter:
from numba import *
sample_array = np.arange(10000.0)
@jit('float64(float64, float64)')
def sum(x, y):
return x + y
sum(sample_array, sample_array)
TypeError Traceback (most recent call last) in () ----> 1 sum(sample_array, sample_array)
C:\Users***\AppData\Local\Continuum\Anaconda\lib\site-packages\numba\dispatcher.pyc in _explain_matching_error(self, *args, **kws) 201 msg = ("No matching definition for argument type(s) %s" 202 % ', '.join(map(str, args))) --> 203 raise TypeError(msg) 204 205 def repr(self):
TypeError: No matching definition for argument type(s) array(float64, 1d, C), array(float64, 1d, C)
NumPy support in Numba comes in many forms: Numba understands calls to NumPy ufuncs and is able to generate equivalent native code for many of them. NumPy arrays are directly supported in Numba. Access to Numpy arrays is very efficient, as indexing is lowered to direct memory accesses when possible.
Numba reads the Python bytecode for a decorated function and combines this with information about the types of the input arguments to the function. It analyzes and optimizes your code, and finally uses the LLVM compiler library to generate a machine code version of your function, tailored to your CPU capabilities.
Creating and returning lists from JIT-compiled functions is supported, as well as all methods and operations. Lists must be strictly homogeneous: Numba will reject any list containing objects of different types, even if the types are compatible (for example, [1, 2.5] is rejected as it contains a int and a float ).
You are passing in arrays, but your jit signature expects scalar floats. Try the following instead:
@jit('float64[:](float64[:], float64[:])')
def sum(x, y):
return x + y
My recommendation is to see if you can get away with not specifying types and just use the bare @jit
decorator, which will do type inference at runtime and you can more flexibly handle inputs. For example:
@jit(nopython=True)
def sum(x, y):
return x + y
In [13]: sum(1,2)
Out[13]: 3
In [14]: sum(np.arange(5),np.arange(5))
Out[14]: array([0, 2, 4, 6, 8])
My experience is that adding the types rarely gives any sort of performance benefit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With