简体   繁体   English

比较 python 中的浮点值,最多保留 3 个小数位

[英]Compare Float values in python upto 3 decimal places

I am using np.isclose() to compare 2 float values but for some usecases this doesn't work as expected.我正在使用np.isclose()比较 2 个浮点值,但对于某些用例,这不能按预期工作。

For example例如

np.isclose([1000.01], [1000.02])

returns True but it should return False .返回True但它应该返回False

I cannot make rtol to 0.0 as I need to compare these values upto 3 decimal places only.我无法将rtol to 0.0 ,因为我只需要将这些值比较到小数点后 3 位。

np.isclose(a, b, rtol=10**-5, atol=10**-8) checks: np.isclose(a, b, rtol=10**-5, atol=10**-8)检查:

np.abs(a - b) <= (atol + rtol * np.abs(b))

This means that for your values ~1000 and the defaults it will return True if the differences are这意味着对于您的值 ~1000 和默认值,如果差异是,它将返回True

<= (10**-8 + 10**-5 * np.abs(1000))
<= 0.01000001

So your values are within that distance, thus it evaluates to True.所以你的值在那个距离之内,因此它的评估结果为真。


If your requirement is如果您的要求是

I need to compare these values up to 3 decimal places only.我只需要将这些值比较到小数点后 3 位。

Then you don't want a relative tolerance, and instead you want only to specify an absolute tolerance.那么您不需要相对容差,而只想指定绝对容差。

np.isclose([1000.01, 1000.0013, 1000.0047, 1000.0041, 1000.0045], 
           [1000.02, 1000.0014, 1000.0052, 1000.0052, 1000.005500001],
           rtol=0, atol=10**-3)

#array([False,  True,  True, False, False])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM