2

我正在尝试将 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++ 时是否有问题?

谢谢你的帮助

4

1 回答 1

4
In [198]: np.float64(1.0).view((np.float32,2))
Out[198]: array([ 0.   ,  1.875], dtype=float32)

所以当

table[y,x] = 1.0

将 anp.float64(1.0)写入tabletable将数据视为np.float32并将其解释为 0 和 1.875。

请注意,0 显示在索引位置[0,1],并1.875显示在索引位置[0,2],而分配发生在[y,x] = [0,1].

您可以通过更改来修复 dtype 不匹配

@numba.jit("void(f8[:,::1],f8[:,::1])")

@numba.jit("void(f4[:,::1],f8[:,::1])")

这些是 8 个字节np.float64(1.0)

In [201]: np.float64(1.0).tostring()
Out[201]: '\x00\x00\x00\x00\x00\x00\xf0?'

当 4 个字节'\x00\x00\xf0?'被解释为 a时np.float32,你得到 1.875:

In [205]: np.fromstring('\x00\x00\xf0?', dtype='float32')
Out[205]: array([ 1.875], dtype=float32)
于 2014-01-31T01:43:47.147 回答