float problem

Gary Herron gherron at islandtraining.com
Wed Sep 24 02:08:37 EDT 2003


On Tuesday 23 September 2003 10:34 pm, Indigo Moon Man wrote:
> for the formula J = I / (12 * 100)  where I is low (like about 8 to 15) I
> get 0.  But when I do it with a calculator it's actually .008333 for
> example if I were 10.  Is there a way I can get python to recognize the
> .008333 instead of it just giving me 0?

You're getting bit by the difference between integer and float
division. 

In versions of python prior to 2.3 (and in 2.3 under normal
circumstances), division of two integers returns an integer and
division of two floats (or a float and an integer )returns a float:
 
>>> 2/3
0
>>> 2/3.0
0.66666666666666663
>>> 2.0/3.0
0.66666666666666663
>>>

So one solution would be to make sure the numbers you are dividing are
floats when you want a float in return.

In future version of Python, there will be two dividion operators:
  / will always return a float
  // will always return an int

In Python 2.3, you can experiment with the future behavior by starting
your program with:
  
>>> from __future__ import division
>>> 2/3
0.66666666666666663
>>> 2//3
0
>>>

So depending on your version of Python, this may be another solution.

Gary Herron







More information about the Python-list mailing list