いくつかの型を追加してコンパイルするだけで、Python関数をcythonに変換しました。Python 関数と cython 関数の結果の間に小さな数値の違いがありました。いくつかの作業の後、違いは int の代わりに unsigned int を使用して numpy 配列にアクセスしたことによるものであることがわかりました。
http://docs.cython.org/src/userguide/numpy_tutorial.html#tuning-indexing-furtherに従って、アクセスを高速化するために unsigned int インデックスを使用していました。
とにかく、unsigned int を使用しても無害だと思いました。
このコードを参照してください:
cpdef function(np.ndarray[np.float32_t, ndim=2] response, max_loc):
cdef unsigned int x, y
x, y = int(max_loc[0]), int(max_loc[1])
x2, y2 = int(max_loc[0]), int(max_loc[1])
print response[y,x], type(response[y,x]), response.dtype
print response[y2,x2], type(response[y2,x2]), response.dtype
print 2*(response[y,x] - min(response[y,x-1], response[y,x+1]))
print 2*(response[y2,x2] - min(response[y2,x2-1], response[y2,x2+1]))
プリント:
0.959878861904 <type 'float'> float32
0.959879 <type 'numpy.float32'> float32
1.04306024313
1.04306030273
なぜこれが起こるのですか?バグですか?
OK、ここで要求されているのは、元の関数で使用したのと同じ型と値を持つ SSCCE です
cpdef function():
cdef unsigned int x, y
max_loc2 = np.asarray([ 15., 25.], dtype=float)
cdef np.ndarray[np.float32_t, ndim=2] response2 = np.zeros((49,49), dtype=np.float32)
x, y = int(max_loc2[0]), int(max_loc2[1])
x2, y2 = int(max_loc2[0]), int(max_loc2[1])
response2[y,x] = 0.959878861904
response2[y,x-1] = 0.438348740339
response2[y,x+1] = 0.753262758255
print response2[y,x], type(response2[y,x]), response2.dtype
print response2[y2,x2], type(response2[y2,x2]), response2.dtype
print 2*(response2[y,x] - min(response2[y,x-1], response2[y,x+1]))
print 2*(response2[y2,x2] - min(response2[y2,x2-1], response2[y2,x2+1]))
版画
0.959878861904 <type 'float'> float32
0.959879 <type 'numpy.float32'> float32
1.04306024313
1.04306030273
私はpython 2.7.3 cython 0.18とmsvc9 expressを使用しています