Atihska
Atihska

Reputation: 5126

How can I compare 2 floating np arrays

I have 2 arrays as follows:

arr1 = array([ 0.40505 ,  0.571486,  0.471516,  0.641669,  0.554498,  0.356352, 0.60921 ,  0.653045,  0.46785 ,  0.42037 ,  0.360116,  0.568134])

arr2 = array([ 0.35635245,  0.55449831,  0.40504998,  0.47151649,  0.57148564, 0.64166886,  0.36011562,  0.56813359,  0.4203698 ,  0.46784994,
        0.6092099 ,  0.65304458])

I am trying to compare these 2 arrays using np.allclose() as follows:

assert np.allclose(arr1.sort(), arr2.sort())

But getting FALSE assertion. How can I compare these. Also, I do no fully understand the np.allclose(). I read that it's used for these purposes but not sure how.

Any help will be really great!

Upvotes: 0

Views: 1561

Answers (2)

cbnaya
cbnaya

Reputation: 1

ndarray.sort does not return value. you can use numpy.sort instead:

assert np.allclose(np.sort(arr1), np.sort(arr2))

Upvotes: 0

Seljuk Gulcan
Seljuk Gulcan

Reputation: 1868

sort method sort the np array in place, it does not return anything. So, you are comparing 2 None.

print(arr1.sort() is None)
>> True

You can sort them before feeding them into allclose function.

arr1.sort()
arr2.sort()
assert np.allclose(arr1, arr2)

This way, it should work.

Upvotes: 3

Related Questions