python - numpy 的按位运算

标签 python python-3.x numpy

假设我有两个 bitboards使用 numpy 数组表示:

import numpy

bitboard = numpy.zeros(2, dtype=numpy.int64)

假设我想设置第一个位板的第 10 位。最快的方法是什么?

<小时/>

我能想到的有两种方法。这是第一种方法:

numpy.bitwise_or(a[0], numpy.left_shift(1, 10), out=a, where=(True, False))

这是第二种方法:

a[0] |= 1 << 10

哪个更快?还有其他方法可以做到这一点吗?我特别想知道:

  1. 当我访问 a[0] 时,numpy 会返回 int64 还是 Python long
  2. 如果它返回一个 Python long,那么我假设这两种方法都非常慢,因为它们适用于任意精度的数字。我的假设正确吗?
  3. 如果是这样,那么有没有办法让按位运算适用于固定精度数字?

请注意,我使用的是 Python 版本 3。

最佳答案

Which one is faster? Is there any other way to do this?

第二种方法更快。

When I access a[0] does numpy return an int64 or a Python long?

它将返回一个 int64

If it returns a Python long then I'm assuming that both methods are pretty slow because they work on arbitrary-precision numbers. Am I right in assuming that?

此线程中的更多详细信息:Slow bitwise operations

关于python - numpy 的按位运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46679536/

相关文章:

python - 收集两列数据

python - 使用 Scipy.opt 进行 Andrew NG Logistic 回归中的形状误差

python - 尝试使用 numpy 在字典中创建给定值的直方图,但并非所有值都显示出来

Python Selenium - 如何处理直到 WebDriverWait 完成后才显示的警报?

python - SciPy 优化器忽略了其中一个约束

python - 如何修复错误 : command 'x86_64-linux-gnu-gcc' failed with exit status 1

python - 在机器人框架中测试完成后,有没有办法在电子邮件中发送 log.html、report.html 和 output.xml?

python - 从 python 使用 ON DUPLICATE KEY UPDATE

Python 多处理线程在处理大量工作时从不加入

python - 我正在尝试将 numpy 数组转换为 PIL.Image。但它给出的是黑色图像。 numpy数组由skimage中的pyramid_gaussian方法返回