numpy
是否在其模块结构的某处有一个 gcd
函数?
我知道 fractions.gcd
但认为 numpy
等价物可能更快,并且可以更好地处理 numpy
数据类型。
除了这个link,我无法在谷歌上发现任何东西这似乎已经过时了,我不知道如何访问它建议存在的 _gcd
函数。
天真地尝试:
np.gcd
np.euclid
对我没用...
最佳答案
你可以自己写:
def numpy_gcd(a, b):
a, b = np.broadcast_arrays(a, b)
a = a.copy()
b = b.copy()
pos = np.nonzero(b)[0]
while len(pos) > 0:
b2 = b[pos]
a[pos], b[pos] = b2, a[pos] % b2
pos = pos[b[pos]!=0]
return a
下面是测试结果和速度的代码:
In [181]:
n = 2000
a = np.random.randint(100, 1000, n)
b = np.random.randint(1, 100, n)
al = a.tolist()
bl = b.tolist()
cl = zip(al, bl)
from fractions import gcd
g1 = numpy_gcd(a, b)
g2 = [gcd(x, y) for x, y in cl]
print np.all(g1 == g2)
True
In [182]:
%timeit numpy_gcd(a, b)
1000 loops, best of 3: 721 us per loop
In [183]:
%timeit [gcd(x, y) for x, y in cl]
1000 loops, best of 3: 1.64 ms per loop
关于python - Numpy gcd 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15569429/