是否将类型强制转换为int32?需要uint16吗?

问题描述 投票:0回答:1

为什么在第二种情况下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)
python numpy casting
1个回答
1
投票

这不一定是错误强制转换,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将假定结果必须转换为负值。

© www.soinside.com 2019 - 2024. All rights reserved.