6

I've been really struggling with numba lately. Copied this code snippet directly from numba docs and it works fine:

@guvectorize([(int64[:], int64, int64[:])], '(n),()->(n)')
def g(x, y, res):
    for i in range(x.shape[0]):
        res[i] = x[i] + y

a = np.arange(5)
g(a,2)

Giving y an array results in a grid. Summing 2 arrays is something I do a lot though, so here's the code I came up with by modifying the snippet.

@guvectorize([(int64[:], int64[:], int64[:])], '(n),(n)->(n)')
def add_arr(x, y, res):
    for i in range(x.shape[0]):
        res[i] = x[i] + y[i]

p = np.ones(1000000)
q = np.ones(1000000)
r = np.zeros(1000000)

add_arr(p,q)

This gives me the error:

TypeError                                 Traceback (most recent call last)
<ipython-input-75-074c0fd345aa> in <module>()
----> 1 add_arr(p,q)

TypeError: ufunc 'add_arr' not supported for the input types, and the      inputs could not be safely coerced to any supported types according to the casting rule ''safe''

I have encountered this error a few times before but I've no idea what it means or how to fix it. How do I get the desired result? Thanks in advance.

4
  • Not strictly familiar with numba, but it seems that you are passing 3 arguments instead of 2 like in the pasted, working example. What happens when you call add_arr(p, q)?
    – korrigan
    Commented Feb 22, 2018 at 3:06
  • @Antoine M Ah dang, I'll edit my code. The same thing happens though. Still get the very same error.
    – Cracin
    Commented Feb 22, 2018 at 3:16
  • Just checking, but you haven't edited the error in your question. It still shows ----> 1 add_arr(p,q,r). You did make sure to reset your environment so you're not running stale bytecode?
    – korrigan
    Commented Feb 22, 2018 at 3:26
  • Sorry, my bad. Got some immediate and now can't seem to edit it on my phone. But yeah, not stale code.
    – Cracin
    Commented Feb 22, 2018 at 3:39

2 Answers 2

5

You are using numpy.ones to generate a list of ones, and according to the documentation (https://docs.scipy.org/doc/numpy/reference/generated/numpy.ones.html):

dtype : data-type, optional

The desired data-type for the array, e.g., numpy.int8. Default is numpy.float64.

np.ones(1000000) is a list of numpy.float64 ones. But your add_arr spec requires lists of int64, hence the TypeError blowing up.

A simple fix:

p = np.ones(1000000, dtype=np.int64)
q = np.ones(1000000, dtype=np.int64)
0
0

This problems might happen when you call a scipy function such as entr. To correct the system behavior you should specify the data type of your input array to float:

from scipy.special import entr
x = np.random.rand(3, 10).astype(float)
print(entr(p))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.