2

How can a function in Cython take two numpy arrays of different types (e.g. one array of ints, the other array of floats) as arguments? The example here http://docs.cython.org/src/userguide/numpy_tutorial.html?highlight=numpy#adding-types shows how to do this for int arrays, but I'd like to have a function like:

import numpy as np
cimport numpy as np
## how do define array types here?
DTYPE = ???
ctypedef np.int_t DTYPE_t
def foo(np.array arr_of_ints, np.array arr_of_floats):
  # divide integers by floats
  result = arr_of_ints / arr_of_floats

How can this be done? thanks.

1 Answer 1

2

Here is an example I cooked up real quick.

import cython
import numpy as np
cimport numpy as np

@cython.boundscheck(False)
def divide(np.ndarray[np.float_t, ndim=1] numer,
           np.ndarray[np.int_t, ndim=1] denom):
    cdef:
        int n = min(numer.shape[0], denom.shape[1])
        np.ndarray[np.float_t, ndim=1] result = np.empty(n, dtype=float)

    for i in range(n):
        result[i] = numer[i] / denom[i]

    return result

I believe most everything above is covered in the link from your question but if you don't understand any of it just ask.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. what is the difference between "cimport numpy as np" and "cimport numpy as cnp" where you keep cnp and np separate? Is there ever a reason to call "cnp.F" where F is a function (like "cnp.empty") over "np.empty"?

Your Answer

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