[Python-ideas] Python Numbers as Human Concept Decimal System
Steven D'Aprano
steve at pearwood.info
Wed Mar 5 14:21:03 CET 2014
On Wed, Mar 05, 2014 at 12:10:18AM -0800, Andrew Barnert wrote:
> Anyone with a middle school expectation will expect 1/3 to be a
> fraction—or, at least, something they can multiply by 3 to get exactly
> 1.
Not a very good example -- that happens to work for Python floats (which
are C doubles under the hood):
py> (1/3)*3 == 1
True
py> (1/3 + 1/3 + 1/3) == 1
True
But it *does not work* with Decimal, at least not with the default
precision:
py> from decimal import Decimal
py> (Decimal(1)/3)*3
Decimal('0.9999999999999999999999999999')
Decimal is not a panacea! It does not eliminate floating point issues.
Between 1 and 100, there are 32 Decimal numbers that fail the test that
(1/n)*n == 1, and only two floats.
Between 1 and 100, there are only four floats where 1/(1/n) does not
equal n: 49 93 98 and 99. In comparison, there are 46 such failing
Decimals, including 6 7 and 9.
--
Steven
More information about the Python-ideas
mailing list