user248237
user248237

Reputation:

using multiple types of numpy arrays in Cython function?

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.

Upvotes: 2

Views: 917

Answers (1)

Bi Rico
Bi Rico

Reputation: 25833

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.

Upvotes: 2

Related Questions