0

So I have a list of floating numbers, some of them have round off errors and appears in the form 0.3599999. It is trivial to detect by convert it to string and see if there is a bunch of 999 following. I wonder how a python hacker will do for this or if there is a mathematical way to do this.

Thanks

4

2 回答 2

2

Consider using Python's decimal module

>>> from decimal import Decimal
>>> Decimal(0.35)
Decimal('0.34999999999999997779553950749686919152736663818359375')
于 2013-03-18T15:15:13.760 回答
1

Also have a look at Numpy's assert_approx_equal() function:

>>> 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
于 2013-03-18T15:20:55.107 回答