Cython 中的函数如何将两个不同类型的 numpy 数组(例如一个整数数组,另一个 float 数组)作为参数?这里的例子http://docs.cython.org/src/userguide/numpy_tutorial.html?highlight=numpy#adding-types展示了如何对 int 数组执行此操作,但我想要一个类似的函数:
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
如何做到这一点?谢谢。
最佳答案
这是我快速编写的一个示例。
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
我相信您问题的链接中涵盖了上述大部分内容,但如果您有任何不明白的地方,请询问。
关于python - 在 Cython 函数中使用多种类型的 numpy 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16026748/