Reputation: 57
This code works perfectly to find the average of the numbers in the file it references however I cannot seem to get it to find the standard deviation. The equation for standard deviation is: Square root/(n1-a)^2+(n2-a)^2/m
-everything is under the square root i could not find the character for it
-N1,N2.....Nm=the numbers that are in the list being referenced
-a=average
-m=total number of numbers in the list
here's what I have,
def main():
numbersFile=open("RandomNumber.txt" , 'r')
line=numbersFile.readline()
total=0
numberoflines=0
while line != "":
numberoflines+=1
total+=int(line)
line=numbersFile.readline().strip()
average=total/numberoflines
std=line-average
deviation=(std**2)/numberoflines
print("The average is: " , average)
print("The standard deviation of the numbers is: " , deviation)
main()
Upvotes: 1
Views: 1602
Reputation: 57
correct source code to calculate:
import math
def main():
numbersFile=open("RandomNumber.txt" , 'r')
line=numbersFile.readline()
total=0
numberoflines=0
while line != "":
numberoflines+=1
total+=float(line)
line=numbersFile.readline().rstrip('\n')
numbersFile.seek(0)
average=total/numberoflines
line=numbersFile.readline()
total=0
while line !="":
line=float(line)-average
a=line**2
total+=a
line=numbersFile.readline()
std=math.sqrt(total/numberoflines)
print("The average is: " , average)
print("The standard deviation of the numbers is: " , std)
main()
Upvotes: 0
Reputation: 1207
Have a look at this question regarding try/except and isdigit(), after that do some casts to float before computing the deviation, something like this:
std=float(line)-float(average)
deviation=float((std**2))/float(numberoflines)
Also keep in mind that your line from line=numbersFile.readline()
might contain characters that are not digits, double check your input. Because you use line in std=line-average
and you know for sure that average is correct, the problem is with line and std gets the wrong value.
Upvotes: 0
Reputation: 106435
Your line
variable is a string returned by file.readline()
. You need to convert it to a float
first before you can perform subtraction with another float.
Change:
std=line-average
to:
std=float(line)-average
Upvotes: 2