在接下来的回答"我可以强迫一个numpy ndarray获取其记忆的所有权吗?" 我尝试PyArray_ENABLEFLAGS
通过Cython的NumPy包装器使用Python C API函数,发现它没有暴露.
以下尝试手动公开它(这只是重现故障的最小示例)
from libc.stdlib cimport malloc
import numpy as np
cimport numpy as np
np.import_array()
ctypedef np.int32_t DTYPE_t
cdef extern from "numpy/ndarraytypes.h":
void PyArray_ENABLEFLAGS(np.PyArrayObject *arr, int flags)
def test():
cdef int N = 1000
cdef DTYPE_t *data = <DTYPE_t *>malloc(N * sizeof(DTYPE_t))
cdef np.ndarray[DTYPE_t, ndim=1] arr = np.PyArray_SimpleNewFromData(1, &N, np.NPY_INT32, data)
PyArray_ENABLEFLAGS(arr, np.NPY_ARRAY_OWNDATA)
Run Code Online (Sandbox Code Playgroud)
失败并出现编译错误:
Error compiling Cython file:
------------------------------------------------------------
...
def test():
cdef int N = 1000
cdef DTYPE_t *data = <DTYPE_t *>malloc(N …
Run Code Online (Sandbox Code Playgroud) 我试图在区间[0,1]中实现高斯分布随机数发生器.
float rand_gauss (void) {
float v1,v2,s;
do {
v1 = 2.0 * ((float) rand()/RAND_MAX) - 1;
v2 = 2.0 * ((float) rand()/RAND_MAX) - 1;
s = v1*v1 + v2*v2;
} while ( s >= 1.0 );
if (s == 0.0)
return 0.0;
else
return (v1*sqrt(-2.0 * log(s) / s));
}
Run Code Online (Sandbox Code Playgroud)
这几乎是Knuth第二卷TAOCP第3版第122页中算法的直接实现.
问题是rand_gauss()有时返回区间[0,1]之外的值.