Luca
Luca

Reputation: 11016

Numpy check where elements of two arrays are approximately equal

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.

Upvotes: 7

Views: 5663

Answers (2)

javidcf
javidcf

Reputation: 59731

What you look for is np.isclose:

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

Upvotes: 13

Thomas Baruchel
Thomas Baruchel

Reputation: 7517

You can always use something relying on:

np.where( np.abs(x-y) < epsilon )

Upvotes: 5

Related Questions