On Dec 4, 2007 8:56 AM, Surjit Nameirakpam <surjit.meitei / gmail.com> wrote:
> How to calculate variance on the elements of an Array

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 = (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}

Another option is to install the NArray library and use that ...

nary = NArray.new(NArray::FLOAT, 100)
nary[0...100] = (1..100).to_a
nary.variance

Blessings,
TwP