Yux*_*ang 2 python precision numpy
我试图在ndarray中找到一个浮点数。由于我使用的软件包(Abaqus),它输出的精度有点低。例如,10类似于10.00003。因此,我想知道是否有一种“正确”的方法可以做到,这比我的代码更整洁。
示例代码:
import numpy as np
array = np.arange(10)
number = 5.00001
Run Code Online (Sandbox Code Playgroud)
如果我这样做?
idx = np.where(number==array)[0][0]
Run Code Online (Sandbox Code Playgroud)
然后结果为空,因为5.00001不等于5。
现在我正在做:
atol = 1e-3 # Absolute tolerance
idx = np.where(abs(number-array) < atol)[0][0]
Run Code Online (Sandbox Code Playgroud)
可以,并且不会太杂乱...但是我想知道是否会有更整洁的方式来做到这一点。谢谢!
PS:这numpy.allclose()是另一种实现方法,但是我需要使用number * np.ones([array.shape[0], array.shape[1]]),对我来说似乎仍然很冗长...
编辑:非常感谢大家的奇妙答案!np.isclose()是我要查找的确切函数,由于它不在文档中,所以我错过了它。如果不是您,我不会意识到这一点,除非他们更新了文档。再次感谢你!
PS:numpy.allclose()是另一种方法,但是我需要使用数字* np.ones([array.shape [0],array.shape [1]]),但对我来说似乎仍然很冗长。 。
您几乎不需要做任何类似的事情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
Run Code Online (Sandbox Code Playgroud)
附带说明一下,如果您确实确实需要一个全为2的数组,则比将2乘以一个简单的方法要多ones:
>>> np.tile(2, array.shape)
array([[2, 2], [2, 2]])
Run Code Online (Sandbox Code Playgroud)
因此,我不知道您为什么需要这样做[array.shape[0], array.shape[1]]。如果数组是2D,则与完全相同array.shape。如果数组可能更大,则与完全相同array.shape[:2]。
我不确定这是否可以解决您的实际问题,因为您似乎想知道哪些关闭或不关闭,而不是仅仅知道它们是否全部。但是您说的事实是,如果不能,则可以使用allclose它来创建要比较的数组太冗长的事实。
因此,如果您需要whereclose而不是allclose…… 那么,没有此功能。但是,建立自己的工作非常容易,并且如果您反复进行操作,则始终可以将其打包。
如果您有一个isclose方法(例如)allclose,但返回的是布尔数组而不是单个布尔值,则可以这样写:
idx = np.where(isclose(a, b, 0, atol))[0][0]
Run Code Online (Sandbox Code Playgroud)
……或者,如果您要一遍又一遍地这样做:
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]
Run Code Online (Sandbox Code Playgroud)
事实证明,numpy 1.7版本确实具有该功能(另请参见此处),但是它似乎不在文档中。如果您不想依赖可能未记录的函数,或者需要使用numpy 1.6,则可以自己编写以下代码:
def isclose(a, b, rtol=1e-05, atol=1e-08):
return np.abs(a-b) <= (atol + rtol * np.abs(b))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1141 次 |
| 最近记录: |