Remove elements out of standard deviation

0

I have the following array [123, 350, 3456, 98] and I need to remove items out of standard deviation, such as 3456 . I already have the standard deviation calculation as below:

class Array
  def average
    return 0 unless self.size > 0
    self.sum / self.size
  end

  def deviation
    average = self.average
    sum = 0
    self.map { |ar| sum += ar - average }
    variance = sum / (self.size - 1)
    Math.sqrt(variance)
  end
end

And to get the deviation just run: [123, 350, 3456, 98].deviation # => 1.0

But now I'm not sure how this might help me in removing 3456 .

    
asked by anonymous 14.04.2015 / 16:25

1 answer

1

See below for operation. Removes array values that are outside the standard deviation:

Add methods in Array class

class Array
  def average
    return 0 unless self.size > 0
    self.sum.to_f / self.size
  end

  def variance
    average = self.average
    sum = 0
    self.map { |ar| sum += (ar - average)**2 }
    sum / (self.size - 1)
  end

  def deviation
    Math.sqrt(self.variance)
  end
end

and then to get the result:

my_array = [123, 350, 3456, 98]
average = my_array.average
deviation = my_array.deviation
my_array.select{ |a| a.between?(average - deviation, average + deviation) }.average
    
15.04.2015 / 16:38