A rational proposal

Nick Coghlan ncoghlan at iinet.net.au
Tue Dec 21 11:19:30 CET 2004


Mike Meyer wrote:
>  I'm willing to do the work to get
> decimals working properly with it.

Facundo's post reminded me of some of the discussion about the interaction 
between floats and Decimal that went on when he was developing the module that 
eventually made it into the standard library.

Perhaps Rational should have the same "arm's length" interaction with floats 
that Decimal does - require the user to set the precision they want by turning 
the float into a string that is then fed to the Rational constructor. My 
argument is that the following behaviour might be a little disconcerting:

Py> x = 1.1
Py> Rational(x)
Rational("11000000000000001 / 10000000000000000")

as opposed to:
Py> x = 1.1
Py> Rational("%.2f" % x)
Rational("11 / 10")

(A direct Decimal->Rational conversion should be OK, however, since it should 
match standard expections regarding the behaviour of the fractional portion)

The other point is that, since converting a Rational to float() or Decimal() may 
lose information, this is something that Python shouldn't really do 
automatically. As Facundo suggested, a string representation is a suitable 
intermediate format that makes explicit the degree of precision used in the 
conversion.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list