Averages/Pythagorean means: Difference between revisions

From Rosetta Code
Content added Content deleted
(Moved second part of task to make it harder to miss)
Line 1: Line 1:
{{task}}
{{task}}
Compute all three of the [[wp:Pythagorean means|Pythagorean means]] of the numbers 1..10.
Compute all three of the [[wp:Pythagorean means|Pythagorean means]] of the numbers 1..10.

Show that <math>A(x_1,\ldots,x_n) \geq G(x_1,\ldots,x_n) \geq H(x_1,\ldots,x_n)</math> for this set of positive numbers.


* The most common, [[Averages/Arithmetic mean|Arithmetic mean]] is the sum of the numbers divided by their count, n:
* The most common, [[Averages/Arithmetic mean|Arithmetic mean]] is the sum of the numbers divided by their count, n:
Line 8: Line 10:
* The [[wp:Harmonic mean|Harmonic mean]] is n divided by the sum of their reciprocals:
* The [[wp:Harmonic mean|Harmonic mean]] is n divided by the sum of their reciprocals:
: <math> H(x_1, \ldots, x_n) = \frac{n}{\frac{1}{x_1} + \cdots + \frac{1}{x_n}} </math>
: <math> H(x_1, \ldots, x_n) = \frac{n}{\frac{1}{x_1} + \cdots + \frac{1}{x_n}} </math>

Show that <math>A(x_1,\ldots,x_n) \geq G(x_1,\ldots,x_n) \geq H(x_1,\ldots,x_n)</math> for this set of positive numbers.


=={{header|Lua}}==
=={{header|Lua}}==

Revision as of 12:37, 21 February 2010

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:

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>

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>