Python – check if two numeric values have same sign in numpy (+/-)

numpy, python

currently i am using numpy.logical_or with numpy.logical_and to check if elements of two arrays have same sign. Was wondering if there is already a ufunc or a more effective method that will achieve this. My current solutions is here

a = np.array([1,-2,5,7,-11,9])b = np.array([3,-8,4,81,5,16])out = np.logical_or(                    np.logical_and((a < 0),(b < 0)),                     np.logical_and((a > 0),(b > 0))                                             )

edit//
output

outOut[51]: array([ True,  True,  True,  True, False,  True], dtype=bool)

Best Solution

One approach with elementwise product and then check for >=0, as same signs (both positive or both negative) would result in positive product values -

((a== b) & (a==0)) | (a*b>0)

Another with explicit sign check -

np.sign(a) == np.sign(b)

Runtime test -

In [155]: a = np.random.randint(-10,10,(1000000))In [156]: b = np.random.randint(-10,10,(1000000))In [157]: np.allclose(np.sign(a) == np.sign(b), ((a== b) & (a==0)) | (a*b>0))Out[157]: TrueIn [158]: %timeit np.sign(a) == np.sign(b)100 loops, best of 3: 3.06 ms per loopIn [159]: %timeit ((a== b) & (a==0)) | (a*b>0)100 loops, best of 3: 3.54 ms per loop# @salehinejad's solnIn [160]: %timeit np.where((np.sign(a)+np.sign(b))==0)100 loops, best of 3: 8.71 ms per loop