微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

按位异或和 NumPy 的意外行为

如何解决按位异或和 NumPy 的意外行为

我有以下玩具代码

import numpy as np


np.random.seed(0)
arr = np.random.randint(0,100,16,dtype=np.uint64)
x = arr.ravel().view(np.uint64)[0]
y = 1
x ^ y

当我尝试运行它时,我得到:

TypeError                                 Traceback (most recent call last)
<ipython-input-2-1b445d429e26> in <module>
      5 x = arr.ravel().view(np.uint64)[0]
      6 y = 1
----> 7 x ^ y

TypeError: ufunc 'bitwise_xor' not supported for the input types,and the inputs Could not be safely coerced to any supported types according to the casting rule ''safe''

这似乎表明按位异或的参数没有支持的类型。 但是,xy 类型分别是 <class 'numpy.uint64'><class 'int'>

print(type(x),type(y))
# <class 'numpy.uint64'> <class 'int'>

如果我用 y = 2 ** 64 - 1 而不是 y = 1 运行完全相同的代码,虽然类型没有改变,但它仍然有效。

无论y 的实际值如何(只要它是整数类型),发生了什么以及如何使此代码工作?


我在 Ubuntu 20.04 上尝试了这个:

  • Python 3.7.10 和 NumPy 1.19.1(conda 环境)
  • Python 3.7.10 和 NumPy 1.19.2(conda 环境)
  • Python 3.8.5 和 NumPy 1.17.4

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。