Search code examples
python-2.7rounding-error

Python rounding error for ints in a list (list contains ints and strings)


I have a python (2.7) script that reads an input file that contains text setup like this:

steve 83 67 77

The script averages the numbers corresponding to each name and returns a list for each name, that contains the persons name along with the average, for example the return output looks like this:

steve 75

However, the actual average value for "steve" is "75.66666667". Because of this, I would like the return value to be 76, not 75 (aka I would like it to round up to the nearest whole integer). I'm not sure how to get this done... Here is my code:

filename = raw_input('Enter a filename: ')
file=open(filename,"r")
line = file.readline()
students=[] 
while line != "":
    splitedline=line.split(" ")
    average=0
    for i in range(len(splitedline)-1) :
        average+=int(splitedline[i+1])
    average=average/(len(splitedline)-1)
    students.append([splitedline[0],average])
    line = file.readline() 

for v in students:
        print " ".join(map(str, v))
file.close()

Solution

  • While your code is very messy and should be improved overall, the solution to your problem should be simple:

    average=average/(len(splitedline)-1)
    

    should be:

    average /= float(len(splitedline) - 1)
    average = int(round(average))
    

    By default in Python 2.x / with two integers does flooring division. You must explicitly make one of the parameters a floating point number to get real division. Then you must round the result and turn it back into an integer.

    In Python 3 flooring division is //, and regular division is /. You can get this behavior in Python 2 with from __future__ import division.