help request

16 views
Skip to first unread message

Sergio Vignali

unread,
Aug 9, 2016, 6:28:41 AM8/9/16
to cython-users
Dear all,

I recently discovered Cython and I am trying to use it in order to speed up some of my scripts.
I think the problem that I run into is easy but I tryed to google it without succes...
In my script I want to sum up the proportion of occurrences in a memory view. I pass to my
function the memory view with the data and another with the values to check. the function
should first count the number of occurrences and then calculate the proportion. Here my script:

cimport cython
from cython.parallel import prange


DTYPE_f64 = np.float64
ctypedef np.float64_t DTYPE_f64_t


@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
@cython.cdivision (True)
cdef int prop(DTYPE_f64_t [:] a, DTYPE_f64_t [:] n) nogil:

cdef Py_ssize_t i ,j
cdef int N = n.shape[0], S = a.shape[0]
cdef int count = 0
cdef double pi = 0.


for i in range(N):
for j in prange(S):
if a[j] == n[i]:
count += 1
pi += (<double>count) / (<double>N)
return pi

if I compile the script I get this error:

Error compiling Cython file:
------------------------------------------------------------
...
    for i in range(N):
        for j in prange(S):
            if a[j] == n[i]:
                count += 1
        pi += (<double>count) / (<double>N)
    return pi
            ^
------------------------------------------------------------

shannon4.pyx:28:13: Cannot assign type 'double' to 'int'

Any suggestion? I really appreciate your help, I am sure that is something simple but till now I didn't find a solution..

All the best
Sergio

Daπid

unread,
Aug 9, 2016, 6:32:37 AM8/9/16
to cython...@googlegroups.com
On 9 August 2016 at 11:11, Sergio Vignali <vignali...@gmail.com> wrote:
> cdef int prop(DTYPE_f64_t [:] a, DTYPE_f64_t [:] n) nogil:
> cdef double pi = 0.
> return pi

You are defining a function as returning an int, but then you return a
double. Change the definition to cdef double prop(...)

/David.
Reply all
Reply to author
Forward
0 new messages