【问题标题】:Best way to detect floating round off error in python在python中检测浮动舍入错误的最佳方法
【发布时间】:2013-03-18 15:00:57
【问题描述】:
所以我有一个浮点数列表,其中一些有四舍五入错误并以0.3599999 的形式出现。通过将其转换为字符串并查看是否有一堆999 来检测是很简单的。我想知道 python 黑客将如何做到这一点,或者是否有数学方法可以做到这一点。
谢谢
【问题讨论】:
标签:
python
floating-point
【解决方案1】:
考虑使用 Python 的十进制模块
>>> from decimal import Decimal
>>> Decimal(0.35)
Decimal('0.34999999999999997779553950749686919152736663818359375')
【解决方案2】:
还可以看看 Numpy 的 assert_approx_equal() 函数:
>>> np.testing.assert_approx_equal(0.12345677777777e-20, 0.1234567e-20)
>>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345671e-20,
significant=8)
>>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345672e-20,
significant=8)
...
<type 'exceptions.AssertionError'>:
Items are not equal to 8 significant digits:
ACTUAL: 1.234567e-021
DESIRED: 1.2345672000000001e-021