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.

0

3 Answers 3

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 
Sign up to request clarification or add additional context in comments.

Comments

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 

Comments

6

Alternatively:

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

This is on by default in Python 3

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.