我试图在 ndarray 中找到一个 float 。由于我使用的软件包(Abaqus),它输出的精度有点低。例如,10 类似于 10.00003。因此,我想知道是否有比我的代码更整洁的“正确”方法。
示例代码:
import numpy as np
array = np.arange(10)
number = 5.00001
如果我这样做:
idx = np.where(number==array)[0][0]
结果为空,因为 5.00001 不等于 5。
现在我在做:
atol = 1e-3 # Absolute tolerance
idx = np.where(abs(number-array) < atol)[0][0]
哪个有效,而且不会太乱......但我想知道是否有更简洁的方法来做到这一点。谢谢!
PS: numpy.allclose()
是另一种方法,但我需要使用 number * np.ones([array.shape[0], array.shape[ 1]])
对我来说它仍然显得冗长......
编辑:非常感谢大家的精彩回答! np.isclose() 是我正在寻找的确切功能,我错过了它,因为它不在文档中......如果不是你们,在他们更新文档之前我不会意识到这一点。再次感谢!
最佳答案
PS: numpy.allclose() is another way to do it, but I need to use number * np.ones([array.shape[0], array.shape[1]]) and it still seems verbose to me...
您几乎不需要做任何类似 number * np.ones([array.shape[0], array.shape[1]])
的事情。正如您可以将标量 number
乘以 ones
数组以将其所有 1
值乘以 number
,您可以将该标量 number
传递给 allclose
以将所有原始数组的值与 number
进行比较。例如:
>>> a = np.array([[2.000000000001, 2.0000000002], [2.000000000001, 1.999999999]])
>>> np.allclose(a, 2)
True
作为旁注,如果您确实确实需要一个全为 2 的数组,有一种比将 2 乘以 ones
更简单的方法:
>>> np.tile(2, array.shape)
array([[2, 2], [2, 2]])
就此而言,我不知道您为什么需要执行 [array.shape[0], array.shape[1]]
。如果数组是二维的,则与 array.shape
完全相同。如果数组可能更大,它与 array.shape[:2]
完全相同。
我不确定这是否解决了您的实际问题,因为您似乎想知道哪些 接近和不接近,而不仅仅是它们是否都接近。但事实上你说你可以使用 allclose
如果不是因为它太冗长而无法创建要比较的数组。
因此,如果您需要 whereclose
而不是 allclose
...那么,没有这样的函数。但是自己构建起来非常容易,而且如果你反复这样做,你总是可以把它包起来。
如果你有一个 isclose
方法——比如 allclose
,但返回一个 bool 数组而不是单个 bool——你可以这样写:
idx = np.where(isclose(a, b, 0, atol))[0][0]
……或者,如果您一遍又一遍地这样做:
def whereclose(a, b, rtol=1e-05, atol=1e-08):
return np.where(isclose(a, b, rtol, atol))
idx = whereclose(a, b, 0, atol)[0][0]
事实证明,numpy 的 1.7 版 does have exactly that function (另请参阅 here ),但它似乎不在文档中。如果您不想依赖可能未记录的函数,或者需要使用 numpy 1.6,您可以自行编写:
def isclose(a, b, rtol=1e-05, atol=1e-08):
return np.abs(a-b) <= (atol + rtol * np.abs(b))
关于python - 在 ndarray 中查找 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18705331/