为什么在第二种情况下numpy将错误地转换为int32?我必须使用第二种情况,因为我使用了一个变量。]
In [24]: np.zeros(10,dtype=np.uint16) - 1
Out[24]: array([65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535], dtype=uint16)
In [23]: np.zeros(10,dtype=np.uint16) + (-1)
Out[23]: array([-1, -1, -1, -1, -1, -1, -1, -1, -1, -1], dtype=int32)
In [26]: np.zeros(10,dtype=np.uint16) + np.uint16(-1)
Out[26]: array([65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535], dtype=uint16)
这不一定是错误强制转换,numpy
试图找到可以处理所有可能结果的最小类型。
您可以用np.result_type
找出结果是什么类型:
np.result_type
使用np.result_type(np.uint16, -1)
>>> int32
np.result_type(np.uint16, 1)
>>> uint16
,结果将是np.zeros(10,dtype=np.uint16) + np.uint16(-1)
,这是强制执行无符号结果所需的操作。否则,uint16
将假定结果必须转换为负值。