Reputation: 43
I am trying to find values in an array created by "arange" by means of "where", but it seems it does not work fine. Here is one example:
from numpy import arange, where
myarr = arange(6.6,10.25,0.05)
for item in [6.6,6.65,6.7,6.8,6.9,6.95,7.95,8.0,8.1,8.15,6.2,6.25,6.35]:
print where(myarr == item)
(array([0]),)
(array([], dtype=int32),)
(array([], dtype=int32),)
(array([], dtype=int32),)
(array([], dtype=int32),)
(array([], dtype=int32),)
(array([], dtype=int32),)
(array([], dtype=int32),)
(array([], dtype=int32),)
(array([], dtype=int32),)
(array([], dtype=int32),)
(array([], dtype=int32),)
(array([], dtype=int32),)
Using Python 2.5.4, Numpy 1.3.0
Thanks in advance!
Upvotes: 4
Views: 3422
Reputation: 880279
Note:
In [32]: repr(myarr[1])
Out[32]: '6.6499999999999995'
In [33]: repr(6.65)
Out[33]: '6.6500000000000004'
So the float64 value that np.arange
assigns to myarr[1]
is not exactly the same float that Python uses to represent 6.65
.
So, unless you really know what you are doing, never test floats for equality. Use inequalities instead:
def near(a,b,rtol=1e-5,atol=1e-8):
try:
return np.abs(a-b)<(atol+rtol*np.abs(b))
except TypeError:
return False
myarr = np.arange(6.6,10.25,0.05)
for item in [6.6,6.65,6.7,6.8,6.9,6.95,7.95,8.0,8.1,8.15,6.2,6.25,6.35]:
print (np.where(near(myarr,item)))
# (array([0]),)
# (array([1]),)
# (array([2]),)
# (array([4]),)
# (array([6]),)
# (array([7]),)
# (array([27]),)
# (array([28]),)
# (array([30]),)
# (array([31]),)
# (array([], dtype=int32),)
# (array([], dtype=int32),)
# (array([], dtype=int32),)
Upvotes: 6