Averages/Pythagorean means

From Rosetta Code
Revision as of 14:53, 21 February 2010 by Underscore (talk | contribs) (Added Haskell.)
Task
Averages/Pythagorean means
You are encouraged to solve this task according to the task description, using any language you may know.

Compute all three of the Pythagorean means of the numbers 1..10.

Show that for this set of positive numbers.

  • The most common, Arithmetic mean is the sum of the numbers divided by their count, n:
  • The Geometric mean is the n'th root of the multiplication of all the numbers:

Haskell

The general function given here yields an arithmetic mean when its first argument is 1, a geometric mean when its first argument is 0, and a harmonic mean when its first argument is -1.

<lang haskell>import Data.List (genericLength) import Control.Monad (zipWithM_)

mean :: Double -> [Double] -> Double mean 0 xs = product xs ** (1 / genericLength xs) mean p xs = (1 / genericLength xs * sum (map (** p) xs)) ** (1/p)

main = zipWithM_ f "agh" (map (flip mean [1 .. 10]) [1, 0, -1])

where f c n = putStrLn $ c : ": " ++ show n</lang>

Lua

<lang lua>function fsum(f, a, ...) return a and f(a) + fsum(f, ...) or 0 end function pymean(t, f, finv) return finv(fsum(f, unpack(t)) / #t) end nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

--arithmetic print(pymean(nums, function(n) return n end, function(n) return n end)) --geometric print(pymean(nums, math.log, math.exp)) --harmonic print(pymean(nums, function(n) return 1/n end, function(n) return 1/n end))</lang>

PL/I

<lang PL/I> declare A(10) float static initial (1,2,3,4,5,6,7,8,9,10); n = hbound(A,1);

/* compute the average */ Average = sum(A)/n;

/* Compute the geometric mean: */ Geometric = prod(A)**(1/n);

/* Compute the Harmonic mean: */ Harmonic = n / sum(1/A);

put skip data (Average); put skip data (Geometric); put skip data (Harmonic); </lang>

Python

<lang Python>>>> from operator import mul >>> from functools import reduce >>> def amean(num): return sum(num)/len(num)

>>> def gmean(num): return reduce(mul, num, 1)**(1/len(num))

>>> def hmean(num): return len(num)/sum(1/n for n in num)

>>> numbers = range(1,11) # 1..10 >>> amean(numbers), gmean(numbers), hmean(numbers) (5.5, 4.528728688116765, 3.414171521474055) >>> assert( amean(numbers) >= gmean(numbers) >= hmean(numbers) ) >>> </lang>