Martinis Group
Martinis Group

Reputation: 213

ndarray comparison

If I compare two ndarrays of type float64, where one of them is empty, I get an empty array of bool:

x = np.array([1.0,2.1]) #dtype is float64
y = np.array([])        #dtype is float64

x==y returns an empty ndarray with dtype of bool.

However, if I compare two ndarrays of type int32, where one of them is empty, I get False:

a = np.array([1,2])
b = np.array([], dtype='int32')

a==b returns False

What gives? Why are the returned types different? What I'm trying to do is compare two ndarrays of type float64.

This is being done on python 2.6.4, numpy 1.6.1, Windows XP

EDIT: "trying to do is compare two ndarrays of type 'float5'" -> "trying to compare two ndarrays of type 'float64'".

Upvotes: 2

Views: 1235

Answers (1)

dwf
dwf

Reputation: 3563

So first of all,

a = np.array([1,2])
b = np.array([], dtype='int32')

a will not necessarily be an int32 array; it will depend on the native integer type of your machine. I can't account for your empty bool array behaviour as I can't reproduce it.

Now, what do you mean by "compare two ndarrays of type float64"? Compare them to see if they are the same shape and if every element is the same? This is a bad idea using == for several reasons.

For one thing, the result when the two are the same shape will not be a boolean but an array of booleans. At the very least you would want to call np.all() on the resulting array.

Also, if one or the other array is the result of some floating point computations, they may be effectively equal but not exactly equal, due to floating point rounding errors. The np.allclose(a1, a2) function is designed for this case (you can specify keyword arguments to change the tolerance levels); it also gracefully returns False if the two arrays have differing shape.

Upvotes: 1

Related Questions