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.
Answer
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
No comments:
Post a Comment