python 3.44 float addition bug?

Stefan Behnel stefan_ml at behnel.de
Thu Jun 26 01:53:52 EDT 2014


Steven D'Aprano, 26.06.2014 04:56:
> On Wed, 25 Jun 2014 14:12:31 -0700, Maciej Dziardziel wrote:
> 
>> Floating points values use finite amount of memory, and  cannot
>> accurately represent infinite amount of numbers, they are only
>> approximations. This is limitation of float type and applies to any
>> languages that uses types supported directly by cpu. To deal with it you
>> can either use decimal.Decimal type that operates using decimal system
>> and saves you from such surprises
> 
> That's a myth. decimal.Decimal *is* a floating point value, and is 
> subject to *exactly* the same surprises as binary floats, except for one: 
> which Decimal, you can guarantee that any decimal string you enter will 
> appear exactly the same (up to the limit of the current precision).
> 
> For example:
> 
> py> x = Decimal(1)/Decimal(23)
> py> x
> Decimal('0.04347826086956521739130434783')
> py> x*23 == 1
> True
> py> sum( [x]*23 ) == 1  # Surprise!
> False
> 
> py> (Decimal(19)/Decimal(17))*Decimal(17) == 19  # Surprise!
> False

It seems that no-one has mentioned the "fractions" module in this thread
yet. It gives you rational numbers (enumerator/denominator), as supposed to
the limited real numbers that floating point numbers represent.

https://docs.python.org/3/library/fractions.html

There are quite a number of use cases for exact calculations where rational
numbers beat any other solution. For the cases above, for example, you'd
get exact results by design. Or in currency calculations, where you want to
move the rounding to the very end and prevent any loss of precision along
the way (unless you're trying to tweak your account in the right direction,
that is).

Stefan





More information about the Python-list mailing list