## 0 Replies - 1304 Views - Last Post: 01 July 2011 - 04:38 PM

### #1 Karel-Lodewijk Reputation: 454
• Posts: 864
• Joined: 17-March 11

# Mean, median mode

Posted 01 July 2011 - 04:38 PM

Description: This snippet extends array to calculate the mean median and mode or a list of numbers. There was already a snippet in the database with the same function but it was incorrect, so I'm posting here a correct version. Note that Mode returns a list as a mode is not necessarily unique. Of course all modes are always equal.
```class Array
def mean
inject(0) {|sum, x| sum += x} / size.to_f
end
def median
sorted = self.sort()
if (sorted.size.modulo(2) == 0) then
((sorted[(sorted.size/2)-1]+sorted[(sorted.size/2)])/2.0)
else
sorted[sorted.size/2]
end
end
def mode
occures = Hash.new(0)
self.each{|x| occures[x] += 1 }
max = 0
modes = []
occures.each{|key, value|
if value > max then
modes = [key]
max = value
elsif value == max
modes.push(key)
end
}
modes
end
end

num_list = [92,86,79,64,89,92,88,62,58,95,100,97]
puts "Mean: #{num_list.mean}"
puts "Median: #{num_list.median}"
puts "Mode: #{num_list.mode}"
```

Is This A Good Question/Topic? 0

Page 1 of 1

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }