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 2 in the following?
JavaScript
x
2
1
c = a / b
2
In 3.x, the behaviour is reversed; see Why does integer division yield a float instead of another integer? for the opposite, 3.x-specific problem.
Advertisement
Answer
In Python 2, division of two ints produces an int. In Python 3, it produces a float. We can get the new behaviour by importing from __future__
.
JavaScript
1
7
1
>>> from __future__ import division
2
>>> a = 4
3
>>> b = 6
4
>>> c = a / b
5
>>> c
6
0.66666666666666663
7