【发布时间】:2014-02-23 14:37:33
【问题描述】:
我正在尝试将 numpy 与 numba 一起使用,但在尝试使用转换为 int 的浮点索引访问或设置一些值到浮点数组时,我得到了奇怪的结果。 检查这个基本功能。
@numba.jit("void(f8[:,::1],f8[:,::1])")
def test(table, index):
x,y = int(index[0,0]), int(index[1,0)
table[y,x] = 1.0
print index[0,0], index[1,0], x,y
print table
print table[y,x]
table = np.zeros((5,5), dtype = np.float32)
index = np.random.ranf(((2,2)))*5
test(table, index)
结果:
index[0,0] = 1.34129550525 index[1,0] = 0.0656177324359 x = 1 y = 0
table[0,1] = 1.0
table [[ 0. 0. 1.875 0. 0. ]
[ 0. 0. 0. 0. 0. ]
[ 0. 0. 0. 0. 0. ]
[ 0. 0. 0. 0. 0. ]
[ 0. 0. 0. 0. 0. ]]
为什么我的表中得到的是 1.875 而不是 1.0?这是一个基本示例,但我正在使用大数组,它给了我很多错误。我知道我可以将索引转换为 np.int32 并更改 @numba.jit("void(f8[:,::1],f8[:,::1])") 到 @numba.jit("void(f8[:,::1],i4[:,::1])") 效果很好,但我愿意像吨一样理解为什么这不起作用。 将类型从python解析为c++时是否有问题?
感谢您的帮助
【问题讨论】:
-
jit中的f8声明和初始化的np.float32是不是有出入? 1.875 不在 x=1 处。顺便说一句,为什么它被标记为 C++?
-
@Joky C++ 标签是一个错误,抱歉。是的,它与 np.float64 一起使用。但是对于像 1.0 这样的数字,float 32 或 float64 应该有所不同吗?
-
既然你标记了 C++ ;) :问题是 table 是一个指向 double 的指针,指向一个 float 数组。为浮点数(大 2 倍)在位置 1 重叠位置 3/4 处写入双精度数,并且在两个浮点数之上编码双精度数没有意义。顺便说一句,这是一个猜测,因为我不确切知道 numba 生成的代码是什么。编辑:unutbu 解释清楚如下。
标签: python numpy casting numba