2013-03-18 66 views
0

所以我有浮動號碼列表,其中一些有舍入誤差,並顯示在表格0.3599999。通過將其轉換爲字符串來檢測是否微不足道,看看下面是否有一堆999。我想知道一個Python黑客會爲此做些什麼,或者如果有一種數學方法來做到這一點。最好的方法來檢測浮動舍入誤差在Python

感謝

+0

http://stackoverflow.com/questions/4028889/floating-在Python中點等於 – Brad 2013-03-18 15:05:05

+2

嘗試e^pi-pi。 http://xkcd.com/217/ – Gandi 2013-03-18 15:25:00

+0

@Gandi:的確,它看起來像[19.99909997919(http://ideone.com/OhFJTy) – jfs 2013-03-18 21:02:40

回答

2

考慮使用Python的十進制模塊

>>> from decimal import Decimal 
>>> Decimal(0.35) 
Decimal('0.34999999999999997779553950749686919152736663818359375') 
1

也看看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