+ 1

Help!! With Averaging Numbers From a Text file in python without using sum()

Hello! I am truly stuck on this question, I can get an *average* with what I have, however, my numbers are way off. The answer is 0.750718518519. But I keep getting 0.7507185185185187. What am I missing? count = 0 total = 0 ### obtaining the file###### fname = input("Enter file name: ") fh = open(fname) ### The loop #### for line in fh: if not line.startswith("X-DSPAM-Confidence:") : continue # Getting the average ##### count = count + 1 lane = line.find(':') fin = line[lane + 1: ] value = float(fin) total = total + value ## Final number##### if count : average = total / count print (average)

17th Jun 2019, 10:57 PM
sheslikethis m
sheslikethis m - avatar
5 Answers
+ 3
Looks like "normal" floating point rounding errors to me. Look into the decimal module for more precision. And don't forget to close your input file đŸ€“
18th Jun 2019, 6:18 AM
Anna
Anna - avatar
+ 2
Your calculator is just truncating the number earlier than python...
17th Jun 2019, 11:10 PM
Jackson O’Donnell
+ 1
Hello Jackson! Thank you for replying. Where do I stop it from doing that???
18th Jun 2019, 12:23 AM
sheslikethis m
sheslikethis m - avatar
+ 1
Easiest would be: print(round(average, x)) Where you replace x with the number of decimal places you want.
18th Jun 2019, 12:35 AM
Jackson O’Donnell
+ 1
Unfortunately no, I am still unable to get the answer: 0.750718518519 With that solution, I get the output: 0.8 Thank you for your help anyway :)
18th Jun 2019, 12:50 AM
sheslikethis m
sheslikethis m - avatar