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
  • 15,954
  • 55
  • 201
  • 355

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,072
  • 10
  • 50
  • 74
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,234
  • 5
  • 46
  • 65
6

Alternatively:

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

This is on by default in Python 3

kwatford
  • 21,848
  • 2
  • 43
  • 60