Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby中标准偏差的平方根和循环_Ruby_Loops_Math - Fatal编程技术网

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

Ruby中标准偏差的平方根和循环,ruby,loops,math,Ruby,Loops,Math,我试图得到每个成员与平均值的差值(例如,给定平均值=4.5)以及使用每个循环得到这两个结果的平方根。按照这个步骤,我所做的是。total=(数组[0]-平均值的平方根)+(数组[1]-平均值)+的平方根…… array = [some values here] average = 4.5 #as example to make the code shorter squaredifference = 0 #Loop through the array, accumulate t

我试图得到每个成员与平均值的差值(例如,给定平均值=4.5)以及使用每个循环得到这两个结果的平方根。按照这个步骤,我所做的是。
total=(数组[0]-平均值的平方根)+(数组[1]-平均值)+的平方根……

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::DomainError:数值参数超出域-“sqrt”
发件人(irb):5:in'sqrt'
from(irb):5:in`block in irb_binding'
发件人(irb):5:在'each'中
来自(irb):5
from/Users/username/.rvm/rubies/ruby-1.9.3-p551/bin/irb:12:in`'

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

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

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

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

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

squared_difference += (num - average)**2
一旦获得了与平均值的所有平方偏差之和,就可以计算总体方差:

variance = squared_difference/n
standard_deviation = Math::sqrt(variance)
其中
n
为人口规模。标准偏差只是方差的平方根:

variance = squared_difference/n
standard_deviation = Math::sqrt(variance)
如果要计算大小为
n
的样本(而非总体)的方差,请使用以下公式:

variance = squared_difference/(n-1)
获得方差的无偏估计。同样,标准偏差是方差的平方根