5.25. Finding the Mean, Median, and Mode of a Data Set

Given an array x, let’s find the mean of all the values in that array. Actually, there are three common kinds of mean. The ordinary or arithmetic mean is what we call the average in everyday life. The harmonic mean is the number of terms divided by the sum of all their reciprocals. And finally, the geometric mean is the nth root of the product of the n values. We show each of these in the following example:

def mean(x) sum=0 x.each {|v| sum += v} sum/x.size end def hmean(x) sum=0 x.each {|v| sum += (1.0/v)} x.size/sum end def gmean(x) prod=1.0 x.each {|v| prod *= v} prod**(1.0/x.size) end data = [1.1, 2.3, 3.3, 1.2, 4.5, 2.1, 6.6] am = mean(data) # 3.014285714 hm = hmean(data) # 2.101997946 ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.