numpy的范围和在哪里 [英] numpy arange and where
本文介绍了numpy的范围和在哪里的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图通过"where"在由"arange"创建的数组中查找值,但似乎无法正常工作.这是一个示例:
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),)
使用Python 2.5.4,Numpy 1.3.0
Using Python 2.5.4, Numpy 1.3.0
提前谢谢!
推荐答案
注意:
In [32]: repr(myarr[1])
Out[32]: '6.6499999999999995'
In [33]: repr(6.65)
Out[33]: '6.6500000000000004'
因此,np.arange
分配给myarr[1]
的float64值与Python用来表示6.65
的float并不完全相同.
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),)
这篇关于numpy的范围和在哪里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文