Working with decimal points

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sat Apr 8 12:05:18 EDT 2006


On Sat, 08 Apr 2006 08:21:06 -0700, Byte wrote:

> How come:
> 
> sum = 1/4
> print sum
> 
> returns 0? 1/4=0.25, not 0. How do I fix this?

By default, / does integer division, not floating point. In integer
division, 1/4 is 0, exactly as calculated. 

(How many fours go into one? Zero fours go into one, with one remainder.)

There are two ways to change this:

(1) Convert at least one of the numbers to a float first:

>>> 1.0/4
0.25
>>> 1/float(4)
0.25

but be careful, this one doesn't do what you want:

>>> float(1/4)
0.0


(2) Run the following command at the start of your program or in your
interactive session:

>>> from __future__ import division

Now division will behave as you expect:

>>> 1/4
0.25

and you can use // for integer division.

Now that you can do floating point division, I peer into my crystal
ball and predict your next question: why is Python so inaccurate?

>>> 1/10
0.10000000000000001

Answer: it isn't. You've discovered a mathematical limitation that 1/10
cannot be written exactly in any fixed number of binary places, just like
1/3 cannot be written exactly in any fixed number of decimal places.

See also:

http://www.python.org/doc/faq/general.html#why-are-floating-point-calculations-so-inaccurate

http://docs.python.org/tut/node16.html


Hope this helps.


-- 
Steven.




More information about the Python-list mailing list