Comparing float and decimal

Nick Craig-Wood nick at craig-wood.com
Wed Sep 24 11:30:03 CEST 2008


Terry Reedy <tjreedy at udel.edu> wrote:
>  The new fractions module acts differently, which is to say, as most 
>  would want.
> 
>  >>> from fractions import Fraction as F
>  >>> F(1) == 1.0
>  True
>  >>> F(1.0)
>  Traceback (most recent call last):
>     File "<pyshell#20>", line 1, in <module>
>       F(1.0)
>     File "C:\Program Files\Python30\lib\fractions.py", line 97, in __new__
>       numerator = operator.index(numerator)
>  TypeError: 'float' object cannot be interpreted as an integer

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)

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!

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

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list