On Dec 4, 2007 5:51 PM, Tim Pease <tim.pease / gmail.com> wrote:
> Implement this algorithm <http://mathworld.wolfram.com/Variance.html>.
>
> 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 =3D (1..100).to_a
> mean =3D (ary.inject(0.0) {|s,x| s + x}) / Float(ary.length)
> variance =3D 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 =3D 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 ;) )

--=20
Sergio Gil P=E9rez de la Manga
e-mail > sgilperez / gmail.com
blog > http://www.lacoctelera.com/porras