python - 错误转换为 int32 ?期待 uint16 代替?
问题描述
为什么在第二种情况下 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.uint16, -1)
>>> int32
np.result_type(np.uint16, 1)
>>> uint16
使用np.zeros(10,dtype=np.uint16) + np.uint16(-1)
,结果将是uint16
,这是您需要执行的强制无符号结果的操作。否则,numpy
将假定必须强制转换结果以处理负值。
推荐阅读
- javascript - JavaScript 对象 - 查找一个属性 -> 更改为 true 并将所有其他属性更改为 false
- java - 使用 listView 将工具栏添加到活动
- angular - 从视图中删除重复值 - Angular
- javascript - 如何将计时事件添加到事件侦听器
- java - Android autocompletetextview 建议下拉出现在软键盘下方
- python - 如何在单行中将不同的数据类型作为输入
- ios - 如何知道 UITableView 何时完成 reloadData?
- google-api-js-client - 通过指定 URI、HTTP 方法、标头、内容类型和请求正文来构造您的 HTTP 请求
- c# - C# 舍入以列出值
- python - 获取我公司完成的 DHL 的所有跟踪号