按位异或和 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 (将#修改为@)