about floating number

Alex Martelli aleaxit at yahoo.com
Thu Oct 19 05:49:29 EDT 2000


"Graduate" <g8741082 at ccunix.ccu.edu.tw> wrote in message
news:8sm7qa$1711$1 at reader.ccu.edu.tw...
> when I in python 2.0, I try to use floating number,
>  but I have a proplem like this...
>  >>> a = 2.8
>  >>> a
>  2.7999999999999998
>
>  why? or I forget some step??

Notice the following:

>>> a=2.8
>>> a
2.7999999999999998
>>> print a
2.8
>>> str(a)
'2.8'
>>> repr(a)
'2.7999999999999998'
>>>

See the difference?  repr(a) strives to give all digits
it possibly can -- and that is what gets used when you
just enter a at the interactive interpreter prompt. str(a)
is not so eager, and is more oriented towards a 'readable'
output than a complete one -- and that is what gets used
when you use the print statement.

Python, like almost all modern computer environments, uses
*binary* representation for numbers.  There is no exact,
finite representation in base two for the fraction 28/10
(14/5) because 5 is not a power of 2 (just like, say, there
is no exact, finite representation in base 10 for the
fraction 1/3, because 3 is not a power of 10).

Not all fractional numbers with exact, finite representation
in base 10 have exact, finite representation in base 2
(since 10 has a prime factor, 5, which 2 lacks).  This
often confuses beginners, because most computer tools
may accept base-10 input but really store their data in
base-2 (or, equivalently, a base that's a power of 2).

For most uses, this is OK -- just remember to use print
(or str(), or the %-operator) and not repr.  If you really
need decimal (base-10) numbers, I think there are some
modules you can get them from (but for financial arithmetic
it's normally better to do the arithmetic in integer terms,
in the smaller unit -- e.g., integer arithmetic in cents
rather than fractional arithmetic in dollars; Python's "long"
integers offer "unlimited" precision, though no fractional
part).


Alex






More information about the Python-list mailing list