Ruby 中标准差的平方根和循环

Square root and Looping on Standard Deviation in Ruby

我正在尝试获取每个成员与平均值(例如,给定平均值 = 4.5)的差异,以及使用每个循环计算这两个结果的平方根。按照 link 上的步骤,我所做的是。 total = square root of (array[0] - average) + square root of (array[1] - average) + ...

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

任何帮助都会很棒。谢谢。

错误是因为您给 Math::sqrt 一个负数作为参数。

要计算 numaverage 的差值,请使用其绝对值:

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

问题不在于您试图计算负数的平方根,而在于您应该计算该数字的 平方。你想要:

squared_difference += (num - average)**2

一旦你得到所有偏离均值的平方和,你就可以计算总体方差:

variance = squared_difference/n

其中 n 是人口规模。标准差就是方差的平方根:

standard_deviation = Math::sqrt(variance)

如果要计算大小为 n 样本 (而不是总体)的方差,请使用公式:

variance = squared_difference/(n-1)

以获得方差的无偏估计量。同样,标准偏差是方差的平方根。