Floating numbers

Mark Dickinson dickinsm at gmail.com
Fri Aug 13 12:01:25 CEST 2010


On Aug 12, 9:43 pm, Bradley Hintze <bradle... at aggiemail.usu.edu>
wrote:
> Hi all.
>
> Is there a way I can keep my floating point number as I typed it? For
> example, I want 34.52 to be 34.52 and NOT 34.5200000002.

Nitpick: unless you're on very unusual hardware, you're missing some
zeros here.  On my machine, under Python 2.6, the float 34.52 displays
as 34.520000000000003, and the value stored internally is actually
34.52000000000000312638803734444081783294677734375;  so that's within
1 part in 10**16 of the value you entered.

Why do you care?  That's a serious question, and its answer goes a
long way to determining what you should do.

 - If you're doing calculations with this number, then the difference
between the number Python stores and 34.52 is so miniscule that in
normal situations it's not going to matter.  In particular, if it
represents some physical quantity then any error in the representation
will be swamped by the inherent measurement error.  IOW, it's not
worth worrying about.

 - If you're printing this number, and you just want the output to
look nice (why?  perhaps because you're showing this to other
people?), then use float formatting operations to limit the number of
decimal places you're printing.  For example, '%.6f' % my_float, or
format(my_float, '.6f'), will give my_float to 6 places after the
decimal point.  Or, as others have mentioned, it just so happens that
Python 2.7 and 3.x will output a nice representation for this float
automatically.  That wouldn't necessarily be true if the result were
coming from a calculation, though, so you shouldn't rely on repr
producing nice results in those versions of Python.

 - If you *really* need a number that represents the *exact* value
34.52, then use the decimal module, or perhaps consider using a simple
home-brewed fixed-point representation.  One situation where you might
care is when doing financial calculations, and in particular when
rounding a quantity to a smaller number of decimal digits.  Here
binary floats can give unpredictable results in halfway cases. (E.g.,
round(2.675, 2) might give 2.68 or 2.67, depending on what version of
Python you're using, and also possibly depending on your platforms.)

--
Mark



More information about the Python-list mailing list