Remove elements outside the standard deviation

Asked

Viewed 121 times

0

I have the following array [123, 350, 3456, 98] and need to remove items outside the standard deviation as in this case the 3456. I have already calculated the standard deviation 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 bypass just run: [123, 350, 3456, 98].deviation # => 1.0

But now I don’t know how it could help me to remove the 3456.

1 answer

1


Follows below in operation. Removes array values that are outside the standard deviation:

Add methods in the 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.