I wrote a program which finds the average and standard deviation of a large data set which is in a separate txt file. I want this program to work with any data set. I tested my program by putting in two simple data points (year and month correlating to a temperature):
2009-11,20 2009-12,10
When running this it says that my the average is 20 and the standard deviation is 0 (obviously wrong).
Here is my program:
data = File.open("test.txt", "r+")
contents = data.read
contents = contents.split("\r\n")
#split up array
contents.collect! do |x|
x.split(',')
end
sum = 0
contents.each do |x|
#make loop to find average
sum = sum + x[1].to_f
end
avg = sum / contents.length
puts "The average of your large data set is: #{ avg.round(3)} (Answer is rounded to nearest thousandth place)"
#puts average
#similar to finding average, this finds the standard deviation
variance = 0
contents.each do |x|
variance = variance + (x[1].to_f - avg)**2
end
variance = variance / contents.length
variance = Math.sqrt(variance)
puts "The standard deviation of your large data set is:#{ variance.round(3)} (Answer is rounded to nearest thousandth place)"