1
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.

alphanumeric
  • 17,967
  • 64
  • 244
  • 392

3 Answers3

6

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
mhlester
  • 22,781
  • 10
  • 52
  • 75
6

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
Valentin Lorentz
  • 9,556
  • 6
  • 47
  • 69
6

Alternatively:

>>> from __future__ import division
>>> 1/50
0.02

This is on by default in Python 3

kenm
  • 23,127
  • 2
  • 43
  • 62