about floating number
aleaxit at yahoo.com
Thu Oct 19 11:49:29 CEST 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
> why? or I forget some step??
Notice the following:
>>> print a
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
More information about the Python-list