我编写了一个程序,您可以在其中找到存储在另一个txt文件中的数据的平均值和标准差。但是,有时我运行它会得到一个错误,说它无法将浮点数转换为数组:
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>'
这是一行:
variance = variance + (x-avg)**2
这是该计划:
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.length
variance = Math.sqrt(variance)
puts variance
答案 0 :(得分:1)
由于您的平均值仅基于x[1]
,因此我认为这些值非常重要。在这种情况下,只需使用x[1].to_f
,就像你所做的那样:
variance = variance + (x[1].to_f - avg)**2