Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple sum-function in Python with numba doesn't compute

Tags:

python

numba

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)

like image 999
JimBoy Avatar asked Oct 07 '15 13:10

JimBoy


People also ask

Does Numba work with NumPy?

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.

How does Numba work in Python?

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.

Can Numba work with lists?

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 ).


1 Answers

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.

like image 63
JoshAdel Avatar answered Oct 29 '22 14:10

JoshAdel