numpy gcd功能 [英] Numpy gcd function
本文介绍了numpy gcd功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
numpy
在其模块结构的某处是否具有gcd
功能?
Does numpy
have a gcd
function somewhere in its structure of modules?
我知道fractions.gcd
,但认为numpy
等效项可能更快并且可以更好地与numpy
数据类型一起使用.
I'm aware of fractions.gcd
but thought a numpy
equivalent maybe potentially quicker and work better with numpy
datatypes.
除了这个链接似乎已过时,我不知道如何访问它暗示存在的_gcd
函数.
I have been unable to uncover anything on google other than this link which seems out of date and I don't know how I would access the _gcd
function it suggests exists.
天真地尝试:
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
以下是测试结果和速度的代码:
Here is the code to test the result and speed:
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
这篇关于numpy gcd功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文