From: "Sergio Gil PĂ©rez de la Manga" Date: 2007-12-05T21:44:47+09:00 Subject: Re: How to calculate variance On Dec 4, 2007 5:51 PM, Tim Pease wrote: > Implement this algorithm . > > 1) iterate over each element and calculate the mean of the elements of > your Array > 2) iterate again over each element and take the difference of each > element with the mean, square that value, and then add it to a running > total > 3) that running total is your variance > > ary = (1..100).to_a > mean = (ary.inject(0.0) {|s,x| s + x}) / Float(ary.length) > variance = ary.inject(0.0) {|s,x| s + (x - mean)**2} You can also write this, if you are going to need it in more places, in a more generic way: module Variance def sum(&blk) map(&blk).inject { |sum, element| sum + element } end def mean (sum.to_f / size.to_f) end def variance m = mean sum { |i| ( i - m )**2 } / size end def std_dev Math.sqrt(variance) end end Array.send :include, Variance puts [1, 2].sum # 3 puts [1, 2].mean # 1.5 puts [1, 2].variance # 0.25 puts [1, 2].std_dev # 0.5 Longer but nicer (maybe ;) ) -- Sergio Gil Pérez de la Manga e-mail > sgilperez@gmail.com blog > http://www.lacoctelera.com/porras