我写了一个程序,它在一个单独的txt文件中查找数据,然后给出平均值和标准偏差。它找到了我的平均值,但我得到标准偏差的错误。想知道有谁可以帮我修复我的代码。就是这样:
data = File.open("avg_temp.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 temperature of Laguardia Airport from 11/97 - 05/11 is:
#{ avg.round(3)}C (Answer is rounded to nearest thousandth place)"
#puts average
variance = 0
contents.each do |x|
variance = variance + (x-avg)**2
end
variance = variance / contents
variance = Math.sqrt(variance)
puts variance
我在第27行遇到错误:variance = variance +(x-avg)** 2
avg_temp.rb:27:in `-': can't convert Float into Array (TypeError)
from avg_temp.rb:27:in `block in <main>'
from avg_temp.rb:26:in `each'
from avg_temp.rb:26:in `<main>'
答案 0 :(得分:6)
当你的问题得到解答时,也许我可以建议一种使用Ruby计算样本均值和标准差的典型方法:
contents = [1,2,3,4,5,6,7,8,9]
n = contents.size # => 9
contents.map!(&:to_f) # => [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
mean = contents.reduce(&:+)/n # => 5.0
sum_sqr = contents.map {|x| x * x}.reduce(&:+) # => 285.0
std_dev = Math.sqrt((sum_sqr - n * mean * mean)/(n-1)) # => 2.7386127875258306
.round(2)
。 答案 1 :(得分:1)
使用
variance = variance / contents.size # or contents.length