18

I can't seem to find the answer to this on this site, though it seems like it would be common enough. I am trying to output a double for the ratio of number of lines in two files.

#Number of lines in each file
inputLines = sum(1 for line in open(current_file))
outputLines = sum(1 for line in open(output_file))

Then get the ratio:

ratio = inputLines/outputLines

But the ratio always seems to be an int and rounds even if I initialize it like:

ratio = 1.0

Thanks.

0

4 Answers 4

33

In python 2, the result of a division of two integers is always a integer. To force a float division, you need to use at least one float in the division:

ratio = float(inputLines)/outputLines

Be careful not to do ratio = float(inputLines/outputLines): although that results in a float, it's one obtained after doing the integer division, so the result will be "wrong" (as in "not what you expect")

In python 3, the integer division behavior was changed, and a division of two integers results in a float. You can also use this functionality in python 2.7, by putting from __future__ import division in the begging of your files.


The reason ratio = 1.0 does not work is that types (in python) are a property of values, not variables - in other words, variables don't have types.

a= 1.0 # "a" is a float
a= 1   # "a" is now a integer
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, makes sense, thanks.
4

Are you using Python 2.x?

Try using

>>> from __future__ import division
>>> ratio = 2/5
0.4

to get a float from a division.

Initializing with ratio = 1.0 doesn't work because with ratio = inputLines/outputLines you are re-assigning the variable to int, no matter what it was before.

Comments

3

Indeed, Python 2 returns an integer when you divide an integer. You can override this behaviour to work like in Python 3, where int / int = float by placing this at the top of your file:

from __future__ import division

Or better yet, just stop using Python 2 :)

Comments

2

You need to cast one of the terms to a floating point value. Either explicitly by using float (that is ratio = float(a)/b or ratio=a/float(b)) or implicitly by adding 0.0: ratio = (a+0.0)/b.

If using Python 2 you can from __future__ import division to make division not be the integral one but the float one.

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.