Apologies if this has already been asked but why does this:
a=4
b=5
c=float(a/b)
print c
Gives
>>>>
0.0
rather than 0.8?
Apologies if this has already been asked but why does this:
a=4
b=5
c=float(a/b)
print c
Gives
>>>>
0.0
rather than 0.8?
That's because this is an integer division:
>>> 4/5
0
if you want to get 0.8
, cast one of the two to float before the division:
>>> 4/float(5)
0.8
In Python 2, division between 2 integers will return an integer (rounding to the closest integer to 0), in this case, 0
. Your code is basically float(0)
which is 0.0
.
You would need to change one of your values to a float first if you want to return a float.
This behavior is changed in Python 3, where division between 2 integers will return a float, 0.8
in this case.
If you do not want to introduce float in one of the variables. You could do this:
from __future__ import division
4/5
This will give what you are looking for 0.8, without having to introduce floating.
In Python 2 /
returns only integer part if you use two integers - like int(0.8)
. You have to use float ie. float(a)
or 4.0
(shortly 4.
) or * 1.0
print float(4)/5
print 4/float(5)
print 4.0/5
print 4/5.0
print 4./5
print 4/5.
print a*1.0/b # sometimes you can see this method
print a/(b*1.0) # this version need () - without () you get (a/b)*1.0
Because of integer division....dividing two integers will return and integer. The value of 0.8 is truncated to 0.
You need to elevate one of your integers to a float if you want a floating point answer.
E.G.
c = float(a) / b