print 1/50
results to a rounded zero: 0
print float(1/50)
once again returns zero but as a float.
What syntax I should be using to get a right result (0.02) using only stock modules.
print 1/50
results to a rounded zero: 0
print float(1/50)
once again returns zero but as a float.
What syntax I should be using to get a right result (0.02) using only stock modules.
This line:
print float(1/50)
Performs an integer division of 1/50, and then casts it to a float. This is the wrong order, since the integer division has already lost the fractional value.
You need to cast to a float first, before the division, in one of these ways:
float(1)/50
1./50
When you write print float(1/50)
, Python first calculates the value of 1/50
(ie. 0
) and then converts it to a float. That's clearly not what you want.
Here are some ways to do it:
>>> print float(1)/50
0.02
>>> print 1/float(50)
0.02
>>> print float(1)/float(50)
0.02
>>> print 1./50
0.02
>>> print 1/50.
0.02
>>> print 1./50.
0.02
Alternatively:
>>> from __future__ import division
>>> 1/50
0.02
This is on by default in Python 3