Question

I wrote a program where you can find the average and standard deviation of data stored in another txt file. However, ever time I run it I get an error saying that it can't convert the float into an array:

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>'

This is the line:

variance = variance + (x-avg)**2

This is the program:

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
Was it helpful?

Solution

Since your average is based only on x[1], I'll assume those values are what matters. In that case, just use x[1].to_f as you did for the sum:

variance = variance + (x[1].to_f - avg)**2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top