假设我有两个 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
哪个更快?还有其他方法可以做到这一点吗?我特别想知道:
- 当我访问
a[0]
时,numpy 会返回int64
还是 Pythonlong
? - 如果它返回一个 Python
long
,那么我假设这两种方法都非常慢,因为它们适用于任意精度的数字。我的假设正确吗? - 如果是这样,那么有没有办法让按位运算适用于固定精度数字?
请注意,我使用的是 Python 版本 3。
最佳答案
Which one is faster? Is there any other way to do this?
第二种方法更快。
When I access
a[0]
does numpy return anint64
or a Pythonlong
?
它将返回一个 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/