O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

2.8. Finding Mean, Median, and Mode

Problem

You want to find the average of an array of numbers: its mean, median, or mode.

Solution

Usually when people speak of the "average" of a set of numbers they're referring to its mean, or arithmetic mean. The mean is the sum of the elements divided by the number of elements.

	def mean(array)
	  array.inject(array.inject(0) { |sum, x| sum += x } / array.size.to_f
	end

	mean([1,2,3,4])                      # => 2.5
	mean([100,100,100,100.1])            # => 100.025
	mean([-100, 100])                    # => 0.0
	mean([3,3,3,3])                      # => 3.00

The median is the item x such that half the items in the array are greater than x and the other half are less than x. Consider a sorted array: if it contains an odd number of elements, the median is the one in the middle. If the array contains an even number of elements, the median is defined as the mean of the two middle elements.

	def median(array, already_sorted=false)
	  return nil if array.empty?
	  array = array.sort unless already_sorted
	  m_pos = array.size / 2
	  return array.size % 2 == 1 ? array[m_pos] : mean(array[m_pos-1..m_pos])
	end

	median([1,2,3,4,5])                  # => 3
	median([5,3,2,1,4])                  # => 3
	median([1,2,3,4])                    # => 2.5
	median([1,1,2,3,4])                  # => 2
	median([2,3,-100,100])               # => 2.5
	median([1, 1, 10, 100, 1000])        # => 10

The mode is the single most popular item in the array. If a list contains no repeated items, it is not considered to have a mode. If an array contains multiple items at the maximum frequency, it is "multimodal." Depending on your application, you might handle each ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required