views:

1319

answers:

5

I have two integer values a and b, but I need their ratio in floating point. I know that a<b and I want to calculate a/b, so if I use integer division I'll always get 0 with a remainder of a.

How can I force c to be a floating point number in Python when:

c = a / b
+3  A: 
c = a / (b * 1.0)
Pinochle
float(b) is better.
Erin
True. There should be one best way :-).
Pinochle
float(b) is not better if b == 1j (or some other complex number). In that case float(b) would raise a TypeError. The question does say a and b are integers so it won't matter in this case - but the correct workaround in the general case is to multiply one of the arguments by 0.1, see pep 238 - http://www.python.org/dev/peps/pep-0238/.
Tom Dunham
@Tom Dunham, I think you mean multiply by 1.0, not 0.1.
Brian Neal
whoops - yes I did mean 1.0; thanks Brian.
Tom Dunham
+15  A: 

You can cast to float by doing c = a / float(b). If the numerator or denominator is a float, then the result will be also.

strout
+16  A: 
>>> from __future__ import division
>>> a = 4
>>> b = 6
>>> c = a / b
>>> c
0.66666666666666663
Michael Fairley
If you go this route and still need some integer division, you can do it like `a // b`
strout
Note that in Python 3, this is the default behavior.
Sam DeFabbia-Kane
+7  A: 

In Python 3.x, the single slash (/) always means true (non-truncating) division. (The // operator is used for truncating division.) In Python 2.x (2.2 and above), you can get this same behavior by putting a

from __future__ import division

at the top of your module.

newacct
+1  A: 

Just making any of the parameters for division in floating-point format also produces the output in floating-point.

Example:

>>> 4.0/3
1.3333333333333333

or,

>>> 4 / 3.0
1.3333333333333333
Babil