Numpy arange and where

I am trying to find values ​​in an array created by "arange" using "where", but it does not seem to 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!

+3
source share
1 answer

Note:

In [32]: repr(myarr[1])
Out[32]: '6.6499999999999995'

In [33]: repr(6.65)
Out[33]: '6.6500000000000004'

Thus, the float64 value that it np.arangeassigns myarr[1]is not exactly the same value that Python uses for presentation 6.65.

So, if you really don't know what you are doing, never test the float 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),)
+5
source

Source: https://habr.com/ru/post/1783913/


All Articles