float / rounding question

Piet van Oostrum piet at cs.uu.nl
Fri Mar 7 17:12:27 EST 2008


>>>>> casevh <casevh at gmail.com> (C) wrote:

>C> On Feb 25, 2:44 am, helen.m.fl... at gmail.com wrote:
>>> Hi I'm very much a beginner with Python.
>>> I want to write a function to convert celcius to fahrenheit like this
>>> one:
>>> 
>>> def celciusToFahrenheit(tc):
>>> tf = (9/5)*tc+32
>>> return tf
>>> 
>>> I want the answer correct to one decimal place, so
>>> celciusToFahrenheit(12) would return 53.6.
>>> 
>>> Of course the function above returns 53.600000000000001.
>>> 
>>> How do I format it correctly?

>C> That is the normal behavior for binary (radix-2) numbers. Just like it
>C> is impossible write 1/3 exactly as a decimal (radix-10) number, 536/10
>C> cannot be written exactly as a binary number. If you really need
>C> decimal numbers, use the Decimal class.

Sorry to come in so late in this discussion. Although it is correct to say
that many real numbers that have an exact decimal representation cannot be
exactly represented in binary, that is no excuse to print 53.6 as
53.600000000000001. This is just lousy printing and the fact that this kind
of question comes up every week shows that it is confusing to many people.

Python just uses the C library for printing, I presume, and the conversion
routines in the C library are rather simplistic. It is, however, possible
to do better, so that 53.6 -- although internally represented as something
that could be described as 53.600000000000001 -- will actually be printed
as 53.6. Indeed, when reading back the printed value you get the exact
representation as the internal number that was printed, and IMHO, that is
what matters. Apparently there is more than one representation that has
this property. I would guess (but didn't check) that
53.60000000000000100000001 also gives the same number. From all these
representations it would be best to choose the simplest one, i.e. 53.6.
This problem and a solution has been described in one of the classical
computer science publications:

http://portal.acm.org/citation.cfm?id=93559
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list