October 2006
Intermediate to advanced
888 pages
16h 55m
English
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 ...Read now
Unlock full access