2015-04-05 76 views
0

我試圖獲得每個成員與平均值(例如,給定平均值= 4.5)的差異以及這兩個使用每個循環的結果的平方根。按照這個link的步驟,我做的是。該total = square root of (array[0] - average) + square root of (array[1] - average) + ...平方根和Ruby上的標準偏差循環

array = [some values here] 
average = 4.5   #as example to make the code shorter 
squaredifference = 0 
#Loop through the array, accumulate the total of the 
#difference of num and average and of the square root of that result 
array.each { |num| squaredifference += Math::sqrt(num - average) } 
puts squaredifference 

我的錯誤是

Math::DomainError: NumericalNumerical argument is out of domain - "sqrt" 
from (irb):5:in `sqrt' 
from (irb):5:in `block in irb_binding' 
from (irb):5:in `each' 
from (irb):5 
from /Users/username/.rvm/rubies/ruby-1.9.3-p551/bin/irb:12:in `<main>' 

任何幫助將是巨大的。謝謝。

回答

0

錯誤是因爲您給Math::sqrt一個負數作爲參數。

要計算的numaverage的區別使用,其絕對值:

Math::sqrt((num - average).abs) 
2

的問題不在於你正試圖計算負數的平方根,這是你應該計算該號碼的平方。你想:

squared_difference += (num - average)**2 

一旦你偏離平均值所有偏差平方的總和,就可以計算出總體方差:

variance = squared_difference/n 

其中n是人口規模。標準偏差僅僅是方差的平方根:

standard_deviation = Math::sqrt(variance) 

如果要計算尺寸n樣品(而不是羣)的方差,使用以下公式:

variance = squared_difference/(n-1) 

以獲得方差的無偏估計量。同樣,標準偏差是方差的平方根。