2013-10-22 2 views
0

별도의 txt 파일에있는 큰 데이터 세트의 평균 및 표준 편차를 찾는 프로그램을 작성했습니다. 이 프로그램이 어떤 데이터 세트와도 작동하기를 바랍니다. 나는 (온도로 연도와 월의 상관) 두 가지 간단한 데이터 포인트에 넣어 내 프로그램을 테스트 :루비의 평균 및 표준 편차는 어떻게 찾습니까?

 
2009-11,20 
2009-12,10 

이 실행 내 평균이 20이고 표준 편차가 0 (분명히 잘못)이라고 말한다. 당신이 리눅스에 있다면, 그것은 contents.split('\n')을해야한다 : 나는 문제가 OS 의존 \r\n를 사용하여 데이터를 분할에서 오는 생각

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)" 
+0

가능 중복 된 [I 루비의 표준 편차를 할 수있는 방법은?] (http://stackoverflow.com/questions/7749568/how-can-i-do-standard-deviation-in-ruby) –

+1

행 분리 문자가''\ r \ n "'입니까? 이 줄을 다음과 같이 바꾸십시오 :'contents = contents.split (/ [\ r \ n] + /)' –

+0

고맙습니다. – user2759592

답변

1

:

여기 내 프로그램입니다. 어쨌든 IO#each을 사용하여 파일의 모든 행을 반복하고 Ruby가 행 끝 문자를 처리하도록하는 것이 더 나을 것입니다.

data = File.open("test.txt", "r+") 

count = 0 
sum = 0 
variance = 0 

data.each do |line| 
    value = line.split(',')[1] 
    sum = sum + value.to_f 
    count += 1 
end 

avg = sum/count 
puts "The average of your large data set is: #{ avg.round(3)} (Answer is rounded to nearest thousandth place)" 

# We need to get back to the top of the file 
data.rewind 

data.each do |line| 
    value = line.split(',')[1] 
    variance = variance + (value.to_f - avg)**2 
end 

variance = variance/count 
variance = Math.sqrt(variance) 
puts "The standard deviation of your large data set is: #{ variance.round(3)} (Answer is rounded to nearest thousandth place)" 
관련 문제