Comparing float and decimal

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Wed Sep 24 22:37:10 EDT 2008


On Wed, 24 Sep 2008 04:30:03 -0500, Nick Craig-Wood wrote:


> Both the Fraction module and the Decimal module could represent floats
> exactly and reversibly since floats are of the form
> 
>   mantissa * 2**exponent
> 
> which is exactly representable as a fraction (rational) and also as
> 
>   mantissa2 * 10**exponent2
> 
> as to why we don't do this...
> 
> I guess it is to preserve the sanity of the user when they write
> fraction(0.1) or decimal(0.1) did they really mean fraction(1,10),
> decimal("0.1") or the exact representations which are
> decimal("0.1000000000000000055511151231257827021181583404541015625") and
> fraction(3602879701896397,2**55)


I would say that in practice the chances that somebody *actually* wanted 
0.1000000000000000055511151231257827021181583404541015625 when they wrote 
0.1 is about the same as the chances that the BDFL will support braces in 
Python 3.0.

(Hint: "from __future__ import braces")


> Given that we let the exact representations leak out anyway (which
> causes a lot of FAQs in this list), eg
> 
>>>> 0.1
> 0.10000000000000001
> 
> IMHO We should put the exact conversions in for floats to Decimal and
> Fraction by default and add a new section to the FAQ!


But of the reasons for having the Decimal module is to avoid such leaky 
abstractions. Without Decimal (or fraction) there's no obvious way to get 
0.1 exactly. It seems perverse to suggest that by default Decimal should 
deliberately expose the same leaky abstraction that causes so much 
trouble when people use floats.

> In that way people will see floats for what they really are - a crude
> approximation to a rational number ;-)

You can already see that just by printing a float:

>>> 0.3
0.29999999999999999
>>> 0.1
0.10000000000000001


-- 
Steven



More information about the Python-list mailing list