我正在为numpy编写一个新的随机数生成器,当我遇到这个非常奇怪的行为时,根据任意分布生成随机数:
这是test.pyx
#cython: boundscheck=False
#cython: wraparound=False
import numpy as np
cimport numpy as np
cimport cython
def BareBones(np.ndarray[double, ndim=1] a,np.ndarray[double, ndim=1] u,r):
return u
def UntypedWithLoop(a,u,r):
cdef int i,j=0
for i in range(u.shape[0]):
j+=i
return u,j
def BSReplacement(np.ndarray[double, ndim=1] a, np.ndarray[double, ndim=1] u):
cdef np.ndarray[np.int_t, ndim=1] r=np.empty(u.shape[0],dtype=int)
cdef int i,j=0
for i in range(u.shape[0]):
j=i
return r
Run Code Online (Sandbox Code Playgroud)
setup.py
from distutils.core import setup
from Cython.Build import cythonize
setup(name = "simple cython func",ext_modules = cythonize('test.pyx'),)
Run Code Online (Sandbox Code Playgroud)
分析代码
#!/usr/bin/python
from __future__ import division
import …Run Code Online (Sandbox Code Playgroud) 功能
PyObject* PyArray_TypeObjectFromType(int);
Run Code Online (Sandbox Code Playgroud)
将NumPy标量类型(NPY_BOOL,NPY_BYTE,...)的类型编号转换为相应的类型对象.
你如何进行相反的转换,从NumPy标量类型的类型对象到相应的类型号?
编辑:以下代码基于kwatford的答案.它接受类型对象(如int和numpy.int16)和字符串(如"int",u"int"和"int16").
int numpyScalarTypeNumber(PyObject* obj)
{
PyArray_Descr* dtype;
if(!PyArray_DescrConverter(obj, &dtype)) return NPY_NOTYPE;
int typeNum = dtype->type_num;
Py_DECREF(dtype);
return typeNum;
}
Run Code Online (Sandbox Code Playgroud)