Velocity Reviews > Integer Division

# Integer Division

Anjanesh Lekshminarayanan
Guest
Posts: n/a

 06-19-2009
>>> a = 1
>>> b = 25
>>> a / b

0
>>> float(a) / b

0.040000000000000001
>>>

>>> from __future__ import division
>>> a = 1
>>> b = 25
>>> a / b

0.040000000000000001
>>>

In what simple way can I get just 0.04 ?

--
Anjanesh Lekshmnarayanan

Mark Dickinson
Guest
Posts: n/a

 06-19-2009
On Jun 19, 8:22*am, Anjanesh Lekshminarayanan <m...@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.040000000000000000832667268468867405317723751068 115234375

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'

http://docs.python.org/library/strin...#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

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

Mark

Piet van Oostrum
Guest
Posts: n/a

 06-19-2009
>>>>> Anjanesh Lekshminarayanan <> (AL) escribió:

>>>>> a = 1
>>>>> b = 25
>>>>> a / b

>AL> 0
>>>>> float(a) / b

>AL> 0.040000000000000001
>>>>>

>>>>> from __future__ import division
>>>>> a = 1
>>>>> b = 25
>>>>> a / b

>AL> 0.040000000000000001
>>>>>

>AL> In what simple way can I get just 0.04 ?

>>> 0.04

0.040000000000000001
>>>

IIRC, Python 3.1 will give 0.04. But this doesn't mean the answer will
be mathematically equal to 0.04, just that it tries to make it less
painful.
--
Piet van Oostrum <>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: