Integer Division

Mark Dickinson dickinsm at gmail.com
Fri Jun 19 04:12:26 EDT 2009


On Jun 19, 8:22 am, Anjanesh Lekshminarayanan <m... at anjanesh.net>
wrote:
> >>> a = 1
> >>> b = 25
> >>> a / b
> 0
> >>> float(a) / b
>
> 0.040000000000000001

Python typically stores floats in binary, not decimal.  The
value 0.04 isn't exactly representable in binary, so the
division float(1)/25 can't produce 0.04:  what you get instead
is a very good approximation to 0.04.  That's why you're
seeing what you're seeing above.  Note that 0.0400...001 is
*also* just an approximation to the actual value stored, but
it's a better approximation than 0.04.  The exact value stored
is (probably, assuming your machine is typical):

0.040000000000000000832667268468867405317723751068115234375

or, if you prefer, it's:

5764607523034235/144115188075855872

> In what simple way can I get just 0.04 ?

The answer to that depends on what you want and why you
want it.  Do you want a string or a number?  And if you
want a number, does it have to be *exactly* 0.04, or
can your application cope with a tiny error?

If you're trying to get a string and just want things
to look nice, use str() instead of repr(),
or display the value using print.  If you want more control
over the number of digits displayed, use Python's string
formatting:  e.g., in Python 2.6:

>>> format(0.04, '.3f')  # format with 3 places after the point
'0.040'

See the following for more information on format:

  http://docs.python.org/library/string.html#formatstrings

If you're after the number and you *really* need to
be able to manipulate the *exact* value 0.04 in Python
(e.g., because you're doing financial work), you're probably
better off using the Decimal module:

  http://docs.python.org/library/decimal.html

See also:

  http://docs.python.org/tutorial/floatingpoint.html

Mark



More information about the Python-list mailing list