Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy check where elements of two arrays are approximately equal

Tags:

python

numpy

I have two numpy arrays with floating point values and I am trying to find the indices where the numbers are approximately equal (floating point comparisons).

So something like:

x = np.random.rand(3)
y = np.random.rand(3)

x[2] = y[2]

# Do the comparison and it should return 2 as the index

I tried something like

np.where(np.allclose(x, y))

However, this returns an empty array. If I do:

np.where(x == y)  # This is fine.

I tried using a combination of numpy.where and numpy.allclose but could not make it work. Of course, I can do it with a loop but that seems tedious and unpythonic.

like image 777
Luca Avatar asked Dec 14 '22 17:12

Luca


2 Answers

What you look for is np.isclose:

np.where(np.isclose(x, y))
like image 165
jdehesa Avatar answered Dec 29 '22 11:12

jdehesa


You can always use something relying on:

np.where( np.abs(x-y) < epsilon )
like image 23
Thomas Baruchel Avatar answered Dec 29 '22 12:12

Thomas Baruchel