Numpy gcd function Numpy gcd function numpy numpy

Numpy gcd function


You can write it yourself:

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 = 2000a = 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 gcdg1 = numpy_gcd(a, b)g2 = [gcd(x, y) for x, y in cl]print np.all(g1 == g2)TrueIn [182]:%timeit numpy_gcd(a, b)1000 loops, best of 3: 721 us per loopIn [183]:%timeit [gcd(x, y) for x, y in cl]1000 loops, best of 3: 1.64 ms per loop


Public service announcement for anyone using Python 3.5

from math import gcdgcd(2, 4)

And if you want to write it yourself in a one-liner:

def gcd(a: int, b: int): return gcd(b, a % b) if b else a


It seems there is no gcd function yet in numpy. However, there is a gcd function in fractions module. If you need to perform gcd on numpy arrays, you could build a ufunc using it:

gcd = numpy.frompyfunc(fractions.gcd, 2, 1)