7

I am learning Cython. I have problem with passing numpy arrays to Cython and don't really understand what is going on. Could you help me?

I have two simple arrays:

a = np.array([1,2])
b = np.array([[1,4],[3,4]])

I want to compute a dot product of them. In python/numpy everything works fine:

>>> np.dot(a,b)
array([ 7, 12])

I translated the code to Cython (as here: http://docs.cython.org/src/tutorial/numpy.html):

import numpy as np
cimport numpy as np

DTYPE = np.int
ctypedef np.int_t DTYPE_t

def dot(np.ndarray a, np.ndarray b):
    cdef int d = np.dot(a, b)
    return d

It compiled with no problems but returns an error:

>>> dot(a,b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test.pyx", line 8, in test.dot (test.c:1262)
    cdef int d = np.dot(a, b)
TypeError: only length-1 arrays can be converted to Python scalars

Could you tell me why and how to do it correctly? Unfortunately Google was not helpful...

Thanks!

0

1 Answer 1

9

Your result is np.ndarray, not int. It fails trying to convert first one to latter. Do instead

def dot(np.ndarray a, np.ndarray b):
    cdef np.ndarray d = np.dot(a, b)
    return d
Sign up to request clarification or add additional context in comments.

1 Comment

A question more related to the OP's script: are the lines with DTYPE and ctypedef actually necessary for this example? Are they flags used internally somewhere?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.