Averages/Pythagorean means: Difference between revisions

imported>Regattaguru
 
(80 intermediate revisions by 37 users not shown)
Line 1:
[[Category:Geometry]]
{{task}}
Compute all three of the   [[wp:Pythagorean means|Pythagorean means]]   of the set of integers   '''1'''   through   '''10'''   (inclusive).
 
;Task
Show that &nbsp; <big><big><math> A(x_1,\ldots,x_n) \geq G(x_1,\ldots,x_n) \geq H(x_1,\ldots,x_n) </math></big></big> &nbsp; for this set of positive integers.
 
Compute all three of the [[wp:Pythagorean means|Pythagorean means]] of the set of integers <big>1</big> through <big>10</big> (inclusive).
* The most common of the three means, the &nbsp; [[Averages/Arithmetic mean|arithmetic mean]], &nbsp; is the sum of the list divided by its length:
::::: <big><big><math> A(x_1, \ldots, x_n) = \frac{x_1 + \cdots + x_n}{n} </math></big></big>
* The [[wp:Geometric mean|geometric mean]] is the &nbsp; <math>n</math><sup>th</sup> &nbsp; root of the product of the list:
::::: <big><big><math> G(x_1, \ldots, x_n) = \sqrt[n]{x_1 \cdots x_n} </math></big></big>
* The &nbsp; [[wp:Harmonic mean|harmonic mean]] &nbsp; is &nbsp; <big><big><math>n</math></big></big> &nbsp; divided by the sum of the reciprocal of each item in the list:
::::: <big><big><math> H(x_1, \ldots, x_n) = \frac{n}{\frac{1}{x_1} + \cdots + \frac{1}{x_n}} </math></big></big>
 
Show that <big><math>A(x_1,\ldots,x_n) \geq G(x_1,\ldots,x_n) \geq H(x_1,\ldots,x_n)</math></big> for this set of positive integers.
 
* The most common of the three means, the [[Averages/Arithmetic mean|arithmetic mean]], is the sum of the list divided by its length:
;C.f.:
: <big><math> A(x_1, \ldots, x_n) = \frac{x_1 + \cdots + x_n}{n}</math></big>
* [[Averages/Root mean square]]
 
<br><br>
* The [[wp:Geometric mean|geometric mean]] is the <math>n</math>th root of the product of the list:
: <big><math> G(x_1, \ldots, x_n) = \sqrt[n]{x_1 \cdots x_n} </math></big>
 
* The [[wp:Harmonic mean|harmonic mean]] is <math>n</math> divided by the sum of the reciprocal of each item in the list:
: <big><math> H(x_1, \ldots, x_n) = \frac{n}{\frac{1}{x_1} + \cdots + \frac{1}{x_n}} </math></big>
 
 
 
{{task heading|See also}}
 
{{Related tasks/Statistical measures}}
 
<br><hr>
 
=={{header|11l}}==
<syntaxhighlight lang="11l">F amean(num)
R sum(num)/Float(num.len)
F gmean(num)
R product(num) ^ (1.0/num.len)
F hmean(num)
return num.len / sum(num.map(n -> 1.0/n))
V numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(amean(numbers))
print(gmean(numbers))
print(hmean(numbers))</syntaxhighlight>
 
{{out}}
<pre>
5.5
4.52873
3.41417
</pre>
 
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
 
PROC InverseI(INT a,result)
REAL one,x
 
IntToReal(1,one)
IntToReal(a,x)
RealDiv(one,x,result)
RETURN
 
PROC ArithmeticMean(INT ARRAY a INT count REAL POINTER result)
INT i
REAL x,sum,tmp
 
IntToReal(0,sum)
FOR i=0 TO count-1
DO
IntToReal(a(i),x)
RealAdd(sum,x,tmp)
RealAssign(tmp,sum)
OD
IntToReal(count,tmp)
RealDiv(sum,tmp,result)
RETURN
 
PROC GeometricMean(INT ARRAY a INT count REAL POINTER result)
INT i
REAL x,prod,tmp
 
IntToReal(1,prod)
FOR i=0 TO count-1
DO
IntToReal(a(i),x)
RealMult(prod,x,tmp)
RealAssign(tmp,prod)
OD
InverseI(count,tmp)
Power(prod,tmp,result)
RETURN
 
PROC HarmonicMean(INT ARRAY a INT count REAL POINTER result)
INT i
REAL x,sum,tmp
 
IntToReal(0,sum)
FOR i=0 TO count-1
DO
InverseI(a(i),x)
RealAdd(sum,x,tmp)
RealAssign(tmp,sum)
OD
IntToReal(count,tmp)
RealDiv(tmp,sum,result)
RETURN
 
PROC Main()
BYTE i
INT ARRAY a=[1 2 3 4 5 6 7 8 9 10]
REAL result
 
Put(125) PutE() ;clear screen
 
ArithmeticMean(a,10,result)
Print("Arithmetic mean=") PrintRE(result)
GeometricMean(a,10,result)
Print(" Geometric mean=") PrintRE(result)
HarmonicMean(a,10,result)
Print(" Harmonic mean=") PrintRE(result)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Pythagorean_means.png Screenshot from Atari 8-bit computer]
<pre>
Arithmetic mean=5.5
Geometric mean=4.52872861
Harmonic mean=3.41417153
</pre>
 
=={{header|ActionScript}}==
<langsyntaxhighlight ActionScriptlang="actionscript">function arithmeticMean(v:Vector.<Number>):Number
{
var sum:Number = 0;
Line 41 ⟶ 151:
trace("Arithmetic: ", arithmeticMean(list));
trace("Geometric: ", geometricMean(list));
trace("Harmonic: ", harmonicMean(list));</langsyntaxhighlight>
 
=={{header|Ada}}==
 
pythagorean_means.ads:
<langsyntaxhighlight Adalang="ada">package Pythagorean_Means is
type Set is array (Positive range <>) of Float;
function Arithmetic_Mean (Data : Set) return Float;
function Geometric_Mean (Data : Set) return Float;
function Harmonic_Mean (Data : Set) return Float;
end Pythagorean_Means;</langsyntaxhighlight>
 
pythagorean_means.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Numerics.Generic_Elementary_Functions;
package body Pythagorean_Means is
package Math is new Ada.Numerics.Generic_Elementary_Functions (Float);
Line 86 ⟶ 196:
end Harmonic_Mean;
 
end Pythagorean_Means;</langsyntaxhighlight>
 
example main.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Pythagorean_Means;
procedure Main is
Line 101 ⟶ 211:
Float'Image (Geometric_Mean) & " >= " &
Float'Image (Harmonic_Mean));
end Main;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 108 ⟶ 218:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - argc and argv implementation dependent}}
<langsyntaxhighlight lang="algol68">main: (
INT count:=0;
LONG REAL f, sum:=0, prod:=1, resum:=0;
Line 133 ⟶ 243:
printf(($"Geometric mean = "f(real)l$,prod**(1/count)));
printf(($"Harmonic mean = "f(real)l$,count/resum))
)</langsyntaxhighlight>
Lunix command:
a68g Averages_Pythagorean_means.a68 - 1 2 3 4 5 6 7 8 9 10
Line 145 ⟶ 255:
Geometric mean = 4.5287
Harmonic mean = 3.4142
</pre>
 
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">begin
% returns the arithmetic mean of the elements of n from lo to hi %
real procedure arithmeticMean ( real array n ( * ); integer value lo, hi ) ;
begin
real sum;
sum := 0;
for i := lo until hi do sum := sum + n( i );
sum / ( 1 + ( hi - lo ) )
end arithmeticMean ;
% returns the geometric mean of the elements of n from lo to hi %
real procedure geometricMean ( real array n ( * ); integer value lo, hi ) ;
begin
real product;
product := 1;
for i := lo until hi do product := product * n( i );
exp( ln( product ) / ( 1 + ( hi - lo ) ) )
end geometricMean ;
% returns the harminic mean of the elements of n from lo to hi %
real procedure harmonicMean ( real array n ( * ); integer value lo, hi ) ;
begin
real sum;
sum := 0;
for i := lo until hi do sum := sum + ( 1 / n( i ) );
( 1 + ( hi - lo ) ) / sum
end harmonicMean ;
 
real array v ( 1 :: 10 );
for i := 1 until 10 do v( i ) := i;
 
r_w := 10; r_d := 5; r_format := "A"; s_w := 0; % set output format %
 
write( "Arithmetic mean: ", arithmeticMean( v, 1, 10 ) );
write( "Geometric mean: ", geometricMean( v, 1, 10 ) );
write( "Harmonic mean: ", harmonicMean( v, 1, 10 ) )
 
end.</syntaxhighlight>
{{out}}
<pre>
Arithmetic mean: 5.50000
Geometric mean: 4.52872
Harmonic mean: 3.41417
</pre>
 
=={{header|Amazing Hopper}}==
Think about "talk" programming...
<syntaxhighlight lang="amazing hopper">
#include <hopper.h>
 
/* An example of definitions in pseudo-natural language, with synonimous.
These definitions can be inside a definition file (xxxx.h) */
#define getasinglelistof(_X_) {_X_},
#synon getasinglelistof getalistof
#define integerrandomnumbers _V1000_=-1,rand array(_V1000_),mulby(10),ceil,
#define randomnumbers _V1000_=-1,rand array(_V1000_)
#define rememberitin(_X_) _X_=0,cpy(_X_)
#synon rememberitin rememberthisnumbersin
#define rememberas(_X_) mov(_X_)
#define remember(_X_) {_X_}
//#synon remember with ---> this exist in HOPPER.H
#defn nowconsiderthis(_X_) #ATOM#CMPLX,print
#synon nowconsiderthis nowconsider,considerthis,consider,nowputtext,puttext,andprint
#define andprintwithanewline {"\n"}print
#synon andprintwithanewline printwithanewline
//#defn andprint(_X_) #ATOM#CMPLX,print
#define putanewline {"\n"}
#define withanewline "\n"
#define andprintit print
#synon andprintit printit,andprint
#define showit show
#define afterdoingit emptystack?,not,do{ {"I cannot continue due to retentive data "},throw(1001) }
#synon afterdoingit secondly,finally
#define then emptystack?do{ {"I cannot continue because data is missing "},throw(1000) }
/* why "#context" and not "#define"?
becose "#context" need a value in the stack for continue.
Internally, "domeanit" tranform to "gosub(calculatearithmeticmean)",
and "gosub" works only if it finds a data in the stack */
#context calculatethegeometricmean
#synon calculatethegeometricmean calculategeometricmean,getgeometricmean
#context calculatetheharmonicmean
#synon calculatetheharmonicmean calculateharmonicmean,getharmonicmean
#context calculatearitmethicmean
#synon calculatearitmethicmean calculatesinglemean,calculatemean,domeanit
 
main:
consider this ("Arithmetic Mean: ")
get a list of '10,10' integer random numbers; remember this numbers in 'list of numbers';
then, do mean it, and print with a new line.
after doing it, consider ("Geometric Mean: "), remember 'list of numbers', calculate the geometric mean;
then, put a new line, and print it.
/*
Okay. This can be a bit long, if we have to write the program;
But what if we just had to talk, and the language interpreter takes care of the rest?
*/
secondly, now consider ("Harmonic Mean: "), with 'list of numbers', get harmonic mean, and print with a new line.
finally, put text ("Original Array:\n"), and print (list of numbers, with a new line)
exit(0)
.locals
calculate aritmethic mean:
stats(MEAN)
back
calculate the geometric mean:
stats(GEOMEAN)
back
calculatetheharmonicmean:
stats(HARMEAN)
back
</syntaxhighlight>
{{out}}
<pre>
Arithmetic Mean: 5.51
Geometric Mean: 4.47333
Harmonic Mean: 3.29515
Original Array:
4 3 10 6 10 1 1 10 4 1
7 4 5 8 9 7 3 8 1 10
5 5 2 5 8 9 1 5 10 10
6 4 3 5 9 2 6 9 2 9
10 9 3 4 6 2 1 8 10 1
7 5 5 9 9 3 7 9 7 7
9 2 10 1 7 9 3 2 7 4
1 6 2 4 10 7 5 1 5 5
1 2 9 5 10 7 7 6 6 4
3 4 5 2 4 1 10 6 3 7
</pre>
Notice:
<pre>
The line "stats(GEOMEAN)" is identical to:
stats(MULTIPLICATORY),POW BY({1}div by (100))
and...
#defn reciprocalof(_X_) {1},#ATOM#CMPLX,postfix,div,postfix
then:
stats(MULTIPLICATORY),POW BY( reciprocal of (100) )
or...
#defn N-ROOTof(_DATA_,_N_) #ATOM#CMPLX,{1}div by(_N_),postfix,pow,postfix
#define Multiplicatoryof(_DATA_) {_DATA_}stats(MULTIPLICATORY)
then:
N-ROOT of ( Multiplicatory of (list of numbers), 100)
etc.
</pre>
 
=={{header|APL}}==
<syntaxhighlight lang="apl">
<lang APL>
arithmetic←{(+/⍵)÷⍴⍵}
geometric←{(×/⍵)*÷⍴⍵}
Line 161 ⟶ 412:
4.528728688
harmonic x
3.414171521</langsyntaxhighlight>
 
 
=={{header|AppleScript}}==
 
{{trans|JavaScript}}
<syntaxhighlight lang="applescript">-- arithmetic_mean :: [Number] -> Number
<lang AppleScript>on run
on arithmetic_mean(xs)
set {A, G, H} to ¬
map(my test, {arithmetic_mean, geometric_mean, harmonic_mean})
-- sum :: Number -> Number -> Number
return {values:{A, G, H}, inequalities:{|A >= G|:A ≥ G}, |G >= H|:G ≥ H}
script sum
end run
on |λ|(accumulator, x)
 
accumulator + x
on test(f)
end |λ|
mReturn(f)'s lambda({1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
end testscript
 
foldl(sum, 0, xs) / (length of xs)
-- arithmetic_mean :: [Number] -> Number
on arithmetic_mean(ns)
foldl(my sum, 0, ns) / (length of ns)
end arithmetic_mean
 
-- geometric_mean :: [Number] -> Number
on geometric_mean(nsxs)
foldl(my product, 1, ns) ^ (1 / (length of ns))
-- product :: Number -> Number -> Number
script product
on |λ|(accumulator, x)
accumulator * x
end |λ|
end script
foldl(product, 1, xs) ^ (1 / (length of xs))
end geometric_mean
 
-- harmonic_mean :: [Number] -> Number
on harmonic_mean(nsxs)
(length of ns) / (foldl(my addInverse, 0, ns))
-- addInverse :: Number -> Number -> Number
script addInverse
on |λ|(accumulator, x)
accumulator + (1 / x)
end |λ|
end script
(length of xs) / (foldl(addInverse, 0, xs))
end harmonic_mean
 
-- TEST -----------------------------------------------------------------------
-- sum :: Number -> Number -> Number
on run
on sum(accumulator, x)
set {A, G, H} to ap({arithmetic_mean, geometric_mean, harmonic_mean}, ¬
accumulator + x
{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}})
end sum
{values:{arithmetic:A, geometric:G, harmonic:H}, inequalities:¬
{|A >= G|:A ≥ G}, |G >= H|:G ≥ H}
end run
 
-- product :: Number -> Number -> Number
on product(accumulator, x)
accumulator * x
end product
 
-- GENERIC FUNCTIONS ----------------------------------------------------------
-- addInverse :: Number -> Number -> Number
on addInverse(accumulator, x)
accumulator + (1 / x)
end addInverse
 
-- A list of functions applied to a list of arguments
 
-- (<*> | ap) :: [(a -> b)] -> [a] -> [b]
 
on ap(fs, xs)
-- GENERIC FUNCTIONS
set {nf, nx} to {length of fs, length of xs}
 
set acc to {}
-- Fold left - analogous to JavaScript's Array.reduce()
repeat with i from 1 to nf
tell mReturn(item i of fs)
repeat with j from 1 to nx
set end of acc to |λ|(contents of (item j of xs))
end repeat
end tell
end repeat
return acc
end ap
 
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
set mf totell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to mf's lambda|λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
 
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
set mf totell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to mf's lambda|λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
 
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
-- handler function --> first class script object
on mReturn(f)
if class of f is script then return f
script f
else
property lambda : f
end script
property |λ| : f
end mReturn</lang>
end script
 
end if
end mReturn</syntaxhighlight>
{{Out}}
<presyntaxhighlight lang="applescript">{values:{arithmetic:5.5, geometric:4.528728688117, harmonic:3.414171521474},
inequalities:{|A >= G|:true}, |G >= H|:true}</presyntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">arithmeticMean: function [arr]->
average arr
 
geometricMean: function [arr]->
(product arr) ^ 1//size arr
 
harmonicMean: function [arr]->
(size arr) // sum map arr 'i [1//i]
 
print arithmeticMean 1..10
print geometricMean 1..10
print harmonicMean 1..10</syntaxhighlight>
 
{{out}}
 
<pre>5.5
4.528728688116765
3.414171521474055</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">A := ArithmeticMean(1, 10)
G := GeometricMean(1, 10)
H := HarmonicMean(1, 10)
Line 290 ⟶ 583:
Sum += 1 / (a + A_Index - 1)
Return, n / Sum
}</langsyntaxhighlight>
Message box shows:
<pre>
Line 300 ⟶ 593:
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">#!/usr/bin/awk -f
{
x = $1; # value of 1st column
Line 313 ⟶ 606:
print "Geometric mean : ",exp(G/N);
print "Harmonic mean : ",N/H;
}</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
The arithmetic and harmonic means use BBC BASIC's built-in array operations; only the geometric mean needs a loop.
<langsyntaxhighlight lang="bbcbasic"> DIM a(9)
a() = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
PRINT "Arithmetic mean = " ; FNarithmeticmean(a())
Line 340 ⟶ 633:
b() = 1/a()
= (DIM(a(),1)+1) / SUM(b())
</syntaxhighlight>
</lang>
{{out}}
<pre>Arithmetic mean = 5.5
Geometric mean = 4.52872869
Harmonic mean = 3.41417152</pre>
 
=={{header|BQN}}==
<syntaxhighlight lang="bqn">A ← +´÷≠
G ← ≠√×´
H ← A⌾÷
 
⋈⟜(∧´ ¯1⊸↓ ≥ 1⊸↓) (A∾G∾H) 1+↕10</syntaxhighlight>
{{out}}
<pre>⟨ ⟨ 5.5 4.528728688116765 3.414171521474055 ⟩ 1 ⟩</pre>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h> // atoi()
#include <math.h> // pow()
Line 369 ⟶ 671:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C++}}==
<lang cpp>#include <vector>
#include <iostream>
#include <numeric>
#include <cmath>
#include <algorithm>
 
double toInverse ( int i ) {
return 1.0 / i ;
}
 
int main( ) {
std::vector<int> numbers ;
for ( int i = 1 ; i < 11 ; i++ )
numbers.push_back( i ) ;
double arithmetic_mean = std::accumulate( numbers.begin( ) , numbers.end( ) , 0 ) / 10.0 ;
double geometric_mean =
pow( std::accumulate( numbers.begin( ) , numbers.end( ) , 1 , std::multiplies<int>( ) ), 0.1 ) ;
std::vector<double> inverses ;
inverses.resize( numbers.size( ) ) ;
std::transform( numbers.begin( ) , numbers.end( ) , inverses.begin( ) , toInverse ) ;
double harmonic_mean = 10 / std::accumulate( inverses.begin( ) , inverses.end( ) , 0.0 ); //initial value of accumulate must be a double!
std::cout << "The arithmetic mean is " << arithmetic_mean << " , the geometric mean "
<< geometric_mean << " and the harmonic mean " << harmonic_mean << " !\n" ;
return 0 ;
}</lang>
{{out}}
<pre>The arithmetic mean is 5.5 , the geometric mean 4.52873 and the harmonic mean 3.41417 !</pre>
 
=={{header|C sharp|C#}}==
Line 405 ⟶ 678:
{{works with|C sharp|C#|3}}
 
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Diagnostics;
Line 435 ⟶ 708:
// Harmonic mean extension method.
static double Hmean(this IEnumerable<double> n) {
return n.Count() / n.Sum(i => 1.0 / i);
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 444 ⟶ 717:
Geometric mean 4.52872868811677
Harmonic mean 3.41417152147406</pre>
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <vector>
#include <iostream>
#include <numeric>
#include <cmath>
#include <algorithm>
 
double toInverse ( int i ) {
return 1.0 / i ;
}
 
int main( ) {
std::vector<int> numbers ;
for ( int i = 1 ; i < 11 ; i++ )
numbers.push_back( i ) ;
double arithmetic_mean = std::accumulate( numbers.begin( ) , numbers.end( ) , 0 ) / 10.0 ;
double geometric_mean =
pow( std::accumulate( numbers.begin( ) , numbers.end( ) , 1 , std::multiplies<int>( ) ), 0.1 ) ;
std::vector<double> inverses ;
inverses.resize( numbers.size( ) ) ;
std::transform( numbers.begin( ) , numbers.end( ) , inverses.begin( ) , toInverse ) ;
double harmonic_mean = 10 / std::accumulate( inverses.begin( ) , inverses.end( ) , 0.0 ); //initial value of accumulate must be a double!
std::cout << "The arithmetic mean is " << arithmetic_mean << " , the geometric mean "
<< geometric_mean << " and the harmonic mean " << harmonic_mean << " !\n" ;
return 0 ;
}</syntaxhighlight>
{{out}}
<pre>The arithmetic mean is 5.5 , the geometric mean 4.52873 and the harmonic mean 3.41417 !</pre>
 
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">(use '[clojure.contrib.math :only (expt)])
(defn a-mean [coll]
(/ (apply + coll) (count coll)))
(defn g-mean [coll]
(expt (apply * coll) (/ (count coll))))
(defn h-mean [coll]
(/ (count coll) (apply + (map / coll))))
(let [numbers (range 1 11)
a (a-mean numbers) g (g-mean numbers) h (h-mean numbers)]
(println a ">=" g ">=" h)
(>= a g h))</syntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">a = [ 1..10 ]
arithmetic_mean = (a) -> a.reduce(((s, x) -> s + x), 0) / a.length
geometic_mean = (a) -> Math.pow(a.reduce(((s, x) -> s * x), 1), (1 / a.length))
Line 456 ⟶ 775:
 
console.log "A = ", A, " G = ", G, " H = ", H
console.log "A >= G : ", A >= G, " G >= H : ", G >= H</langsyntaxhighlight>
{{out}}
<pre>A = 5.5 G = 4.528728688116765 H = 3.414171521474055
Line 462 ⟶ 781:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun generic-mean (nums reduce-op final-op)
(funcall final-op (reduce reduce-op nums)))
 
Line 484 ⟶ 803:
(format t "a-mean ~a~%" a-mean)
(format t "g-mean ~a~%" g-mean)
(format t "h-mean ~a~%" h-mean)))</langsyntaxhighlight>
 
=={{header|ClojureCraft Basic}}==
<syntaxhighlight lang="basic">precision 6
<lang Clojure>(use '[clojure.contrib.math :only (expt)])
 
define bxsum = 1, sum = 0, sum1i = 0
(defn a-mean [coll]
define average = 0, geometric = 0, harmonic = 0
(/ (apply + coll) (count coll)))
 
for i = 1 to 10
(defn g-mean [coll]
 
(expt (apply * coll) (/ (count coll))))
let sum = sum + i
let bxsum = bxsum * i
(defn h-mean [coll]
let sum1i (/= (count coll) (applysum1i + (map1 / coll)))i)
 
next i
(let [numbers (range 1 11)
 
a (a-mean numbers) g (g-mean numbers) h (h-mean numbers)]
let average = sum / 10
(println a ">=" g ">=" h)
let geometric = bxsum ^ (1 / 10)
(>= a g h))</lang>
let harmonic = 10 / sum1i
 
print "arithmetic mean: ", average
print "geometric mean: ", geometric
print "harmonic mean: ", harmonic
 
if average >= geometric and geometric >= harmonic then
 
print "true"
end
 
endif
 
print "false"</syntaxhighlight>
{{out| Output}}<pre>
arithmetic mean: 5.500000
geometric mean: 4.528729
harmonic mean: 3.414172
true
</pre>
 
=={{header|D}}==
The output for the harmonic mean is wrong.
<lang d>import std.stdio, std.algorithm, std.range, std.functional;
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.functional;
 
auto aMean(T)(T data) pure nothrow @nogc {
Line 522 ⟶ 862:
writefln("%(%.19f %)", m);
assert(m.isSorted);
}</langsyntaxhighlight>
{{out}}
<pre>0.9891573712076470036 4.5287286881167647619 5.5000000000000000000</pre>
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program AveragesPythagoreanMeans;
 
{$APPTYPE CONSOLE}
Line 576 ⟶ 916:
else
writeln("Error!");
end.</langsyntaxhighlight>
 
=={{header|E}}==
Line 582 ⟶ 922:
Given that we're defining all three together, it makes sense to express their regularities:
 
<langsyntaxhighlight lang="e">def makeMean(base, include, finish) {
return def mean(numbers) {
var count := 0
Line 596 ⟶ 936:
def A := makeMean(0, fn b,x { b+x }, fn acc,n { acc / n })
def G := makeMean(1, fn b,x { b*x }, fn acc,n { acc ** (1/n) })
def H := makeMean(0, fn b,x { b+1/x }, fn acc,n { n / acc })</langsyntaxhighlight>
 
<langsyntaxhighlight lang="e">? A(1..10)
# value: 5.5
 
Line 605 ⟶ 945:
 
? H(1..10)
# value: 3.414171521474055</langsyntaxhighlight>
 
=={{header|EasyLang}}==
{{trans|C}}
<syntaxhighlight>
proc mean . v[] a g h .
prod = 1
for v in v[]
sum += v
prod *= v
resum += 1 / v
.
a = sum / len v[]
g = pow prod (1 / len v[])
h = len v[] / resum
.
a[] = [ 1 2 3 4 5 6 7 8 9 10 ]
mean a[] a g h
print a
print g
print h
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(define (A xs) (// (for/sum ((x xs)) x) (length xs)))
 
Line 618 ⟶ 979:
(and (>= (A xs) (G xs)) (>= (G xs) (H xs)))
→ #t
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Means do
def arithmetic(list) do
Enum.sum(list) / length(list)
Line 637 ⟶ 998:
IO.puts "Geometric mean: #{gm = Means.geometric(list)}"
IO.puts "Harmonic mean: #{hm = Means.harmonic(list)}"
IO.puts "(#{am} >= #{gm} >= #{hm}) is #{am >= gm and gm >= hm}"</langsyntaxhighlight>
{{out}}
<pre>
Line 648 ⟶ 1,009:
=={{header|Erlang}}==
 
<langsyntaxhighlight Erlanglang="erlang">%% Author: Abhay Jain <abhay_1303@yahoo.co.in>
 
-module(mean_calculator).
Line 682 ⟶ 1,043:
harmonic_mean(Number, Sum) ->
NewSum = Sum + (1/Number),
harmonic_mean(Number+1, NewSum). </langsyntaxhighlight>
 
{{out}}
Line 690 ⟶ 1,051:
 
=={{header|ERRE}}==
<syntaxhighlight lang="text">
PROGRAM MEANS
 
Line 734 ⟶ 1,095:
PRINT("Harmonic mean = ";M)
END PROGRAM
</syntaxhighlight>
</lang>
 
=={{header|Euler Math Toolbox}}==
 
<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
>function A(x) := mean(x)
>function G(x) := exp(mean(log(x)))
Line 746 ⟶ 1,107:
4.52872868812
3.41417152147
</syntaxhighlight>
</lang>
 
Alternatively, e.g.,
 
<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
>function G(x) := prod(x)^(1/length(x))
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function arithmetic_mean(sequence s)
atom sum
if length(s) = 0 then
Line 806 ⟶ 1,167:
printf(1,"Harmonic: %g\n", harmonic)
printf(1,"Arithmetic>=Geometric>=Harmonic: %s\n",
{true_or_false(arithmetic>=geometric and geometric>=harmonic)})</langsyntaxhighlight>
 
{{out}}
Line 819 ⟶ 1,180:
Use the functions : AVERAGE, GEOMEAN and HARMEAN
 
<syntaxhighlight lang="excel">
<lang Excel>
=AVERAGE(1;2;3;4;5;6;7;8;9;10)
=GEOMEAN(1;2;3;4;5;6;7;8;9;10)
=HARMEAN(1;2;3;4;5;6;7;8;9;10)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 830 ⟶ 1,191:
3,414171521
</pre>
 
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let P = [1.0; 2.0; 3.0; 4.0; 5.0; 6.0; 7.0; 8.0; 9.0; 10.0]
 
let arithmeticMean (x : float list) =
Line 850 ⟶ 1,210:
printfn "Arithmetic Mean: %A" (arithmeticMean P)
printfn "Geometric Mean: %A" (geometricMean P)
printfn "Harmonic Mean: %A" (harmonicMean P)</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">: a-mean ( seq -- mean )
[ sum ] [ length ] bi / ;
 
Line 860 ⟶ 1,220:
 
: h-mean ( seq -- mean )
[ length ] [ [ recip ] map-sum ] bi / ;</langsyntaxhighlight>
 
( scratchpad ) 10 [1,b] [ a-mean ] [ g-mean ] [ h-mean ] tri
Line 868 ⟶ 1,228:
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 910 ⟶ 1,270:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: famean ( faddr n -- f )
0e
tuck floats bounds do
Line 939 ⟶ 1,299:
test 10 fhmean fdup f.
( A G G H )
f>= . f>= . \ -1 -1</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90}}
<langsyntaxhighlight lang="fortran">program Mean
 
real :: a(10) = (/ (i, i=1,10) /)
Line 958 ⟶ 1,318:
end if
 
end program Mean</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
' FB 1.05.0 Win64
 
Function ArithmeticMean(array() As Double) As Double
Dim length As Integer = Ubound(array) - Lbound(array) + 1
Dim As Double sum = 0.0
For i As Integer = LBound(array) To UBound(array)
sum += array(i)
Next
Return sum/length
End Function
 
Function GeometricMean(array() As Double) As Double
Dim length As Integer = Ubound(array) - Lbound(array) + 1
Dim As Double product = 1.0
For i As Integer = LBound(array) To UBound(array)
product *= array(i)
Next
Return product ^ (1.0 / length)
End Function
 
Function HarmonicMean(array() As Double) As Double
Dim length As Integer = Ubound(array) - Lbound(array) + 1
Dim As Double sum = 0.0
For i As Integer = LBound(array) To UBound(array)
sum += 1.0 / array(i)
Next
Return length / sum
End Function
Dim vector(1 To 10) As Double
For i As Integer = 1 To 10
vector(i) = i
Next
 
Print "Arithmetic mean is :"; ArithmeticMean(vector())
Print "Geometric mean is :"; GeometricMean(vector())
Print "Harmonic mean is :"; HarmonicMean(vector())
Print
Print "Press any key to quit the program"
Sleep
</syntaxhighlight>
 
{{out}}
<pre>
Arithmetic mean is : 5.5
Geometric mean is : 4.528728688116765
Harmonic mean is : 3.414171521474055
</pre>
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">import lists.zip
 
def
Line 976 ⟶ 1,387:
println( "$l: $m" + (if m is Rational then " or ${m.doubleValue()}" else '') )
 
println( monotone(means, (>=)) )</langsyntaxhighlight>
 
{{out}}
Line 985 ⟶ 1,396:
Harmonic: 25200/7381 or 3.414171521474055
true
</pre>
 
=={{header|Futhark}}==
 
<syntaxhighlight lang="futhark">
fun arithmetic_mean(as: [n]f64): f64 =
reduce (+) 0.0 (map (/f64(n)) as)
 
fun geometric_mean(as: [n]f64): f64 =
reduce (*) 1.0 (map (**(1.0/f64(n))) as)
 
fun harmonic_mean(as: [n]f64): f64 =
f64(n) / reduce (+) 0.0 (map (1.0/) as)
 
fun main(as: [n]f64): (f64,f64,f64) =
(arithmetic_mean as,
geometric_mean as,
harmonic_mean as)
</syntaxhighlight>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="FutureBasic>
 
Double ari = 1, geo = 0, har = 0
Short i, n = 10
 
for i = 1 to n
ari += i
geo *= i
har += 1 \ i
next
 
print "ari:", ari \ n
print "geo:", geo^( 1 \ n )
print "har:", n \ har
 
handleevents
</syntaxhighlight>
<pre>
 
ari: 5.5
geo: 4.528728688116765
har: 3.414171521474055
 
</pre>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># The first two work with rationals or with floats
# (but bear in mind that support of floating point is very poor in GAP)
mean := v -> Sum(v) / Length(v);
Line 1,005 ⟶ 1,460:
# 3.41417
geomean(v);
# 4.52873</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,024 ⟶ 1,480:
fmt.Println("A:", a, "G:", g, "H:", h)
fmt.Println("A >= G >= H:", a >= g && g >= h)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,033 ⟶ 1,489:
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def arithMean = { list ->
list == null \
? null \
Line 1,055 ⟶ 1,511:
? 0 \
: list.size() / list.collect { 1.0/it }.sum()
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">def list = 1..10
def A = arithMean(list)
def G = geomMean(list)
Line 1,069 ⟶ 1,525:
G: ${G}
H: ${H}
"""</langsyntaxhighlight>
 
{{out}}
Line 1,078 ⟶ 1,534:
 
=={{header|Haskell}}==
====One generalized function====
The [[wp:Generalized mean|general function]] given here yields an arithmetic mean when its first argument is <code>1</code>, a geometric mean when its first argument is <code>0</code>, and a harmonic mean when its first argument is <code>-1</code>.
 
<langsyntaxhighlight lang="haskell">import Data.List (genericLength)
import Control.Monad (zipWithM_)
 
Line 1,090 ⟶ 1,547:
let ms = zipWith ((. flip mean [1..10]). (,)) "agh" [1, 0, -1]
mapM_ (\(t,m) -> putStrLn $ t : ": " ++ show m) ms
putStrLn $ " a >= g >= h is " ++ show ((\(_,[a,g,h])-> a>=g && g>=h) (unzip ms))</langsyntaxhighlight>
 
====Three applicatively defined functions====
These three functions (each combining the length of a list with some kind of fold over the elements of that same list), all share the same applicative structure.
 
<syntaxhighlight lang="haskell">import Data.List (genericLength)
 
-- ARITHMETIC, GEOMETRIC AND HARMONIC MEANS ---------------
arithmetic, geometric, harmonic :: [Double] -> Double
arithmetic = (/) . sum <*> genericLength
 
geometric = (**) . product <*> ((1 /) . genericLength)
 
harmonic = (/) . genericLength <*> foldr ((+) . (1 /)) 0
 
-- TEST ---------------------------------------------------
xs :: [Double]
xs = [arithmetic, geometric, harmonic] <*> [[1 .. 10]]
 
main :: IO ()
main =
(putStrLn . unlines)
[ zip ["Arithmetic", "Geometric", "Harmonic"] xs >>= show
, mappend "\n A >= G >= H is " $ --
(show . and) $ zipWith (>=) xs (tail xs)
]</syntaxhighlight>
{{Out}}
<pre>("Arithmetic",5.5)("Geometric",4.528728688116765)("Harmonic",3.414171521474055)
 
a >= g >= h is True</pre>
 
=={{header|HicEst}}==
<langsyntaxhighlight HicEstlang="hicest">AGH = ALIAS( A, G, H ) ! named vector elements
AGH = (0, 1, 0)
DO i = 1, 10
Line 1,102 ⟶ 1,588:
AGH = (A/10, G^0.1, 10/H)
 
WRITE(ClipBoard, Name) AGH, "Result = " // (A>=G) * (G>=H)</langsyntaxhighlight>
! A=5.5; G=4.528728688; H=3.414171521; Result = 1;
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">link numbers # for a/g/h means
 
procedure main()
Line 1,117 ⟶ 1,603:
write(" a >= g >= h is ", if a >= g >= h then "true" else "false")
end
</syntaxhighlight>
</lang>
 
{{libheader|Icon Programming Library}}
[http://www.cs.arizona.edu/icon/library/src/procs/numbers.icn numbers:amean, numbers:gmean, and numbers:hmean] are shown below:
<langsyntaxhighlight Iconlang="icon">procedure amean(L[]) #: arithmetic mean
local m
if *L = 0 then fail
Line 1,150 ⟶ 1,636:
}
return *L / m
end</langsyntaxhighlight>
 
{{out}}
Line 1,159 ⟶ 1,645:
Harmonic mean:3.414171521474055
a >= g >= h is true</pre>
 
=={{header|IS-BASIC}}==
<syntaxhighlight lang="is-basic">100 PROGRAM "Averages.bas"
110 NUMERIC ARR(1 TO 10)
120 FOR I=LBOUND(ARR) TO UBOUND(ARR)
130 LET ARR(I)=I
140 NEXT
150 PRINT "Arithmetic mean =";ARITHM(ARR)
160 PRINT "Geometric mean =";GEOMETRIC(ARR)
170 PRINT "Harmonic mean =";HARMONIC(ARR)
180 DEF ARITHM(REF A)
190 LET T=0
200 FOR I=LBOUND(A) TO UBOUND(A)
210 LET T=T+A(I)
220 NEXT
230 LET ARITHM=T/SIZE(A)
240 END DEF
250 DEF GEOMETRIC(REF A)
260 LET T=1
270 FOR I=LBOUND(A) TO UBOUND(A)
280 LET T=T*A(I)
290 NEXT
300 LET GEOMETRIC=T^(1/SIZE(A))
310 END DEF
320 DEF HARMONIC(REF A)
330 LET T=0
340 FOR I=LBOUND(A) TO UBOUND(A)
350 LET T=T+(1/A(I))
360 NEXT
370 LET HARMONIC=SIZE(A)/T
380 END DEF</syntaxhighlight>
 
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight lang="j">amean=: +/ % #
gmean=: # %: */
hmean=: amean&.:%</langsyntaxhighlight>
 
'''Example Usage:'''
<langsyntaxhighlight lang="j"> (amean , gmean , hmean) >: i. 10
5.5 4.528729 3.414172
assert 2 >:/\ (amean , gmean , hmean) >: i. 10 NB. check amean >= gmean and gmean >= hmean</langsyntaxhighlight>
 
Note that gmean could have instead been defined as mean under logarithm, for example:
 
<langsyntaxhighlight lang="j">gmean=:amean&.:^.</langsyntaxhighlight>
 
(and this variant should probably be preferred - especially if the argument list is long, to avoid problems with floating point infinity.)
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.util.Arrays;
import java.util.List;
 
Line 1,216 ⟶ 1,735:
System.out.format("A >= G is %b, G >= H is %b%n", (arithmetic >= geometric), (geometric >= harmonic));
}
}</langsyntaxhighlight>
{{out}}
<pre>A = 5.500000 G = 4.528729 H = 3.414172
Line 1,223 ⟶ 1,742:
{{works with|Java|1.8}}
We can rewrite the 3 methods using the new JAVA Stream API:
<langsyntaxhighlight lang="java">
public static double arithmAverage(double array[]){
if (array == null ||array.length == 0) {
Line 1,260 ⟶ 1,779:
}
}
</langsyntaxhighlight>
 
=={{header|JavaScript}}==
{{works with|ES5}}
 
===ES5===
<lang javascript>(function () {
<syntaxhighlight lang="javascript">(function () {
'use strict';
 
Line 1,325 ⟶ 1,844:
 
})();
</syntaxhighlight>
</lang>
 
{{Out}}
<syntaxhighlight lang="javascript">{
<lang JavaScript>{
"values": {
"Arithmetic": 5.5,
Line 1,335 ⟶ 1,854:
},
"test": "is A >= G >= H ? yes"
}</langsyntaxhighlight>
 
===ES6===
<syntaxhighlight lang="javascript">(() => {
 
// arithmeticMean :: [Number] -> Number
const arithmeticMean = xs =>
foldl((sum, n) => sum + n, 0, xs) / length(xs);
 
// geometricMean :: [Number] -> Number
const geometricMean = xs =>
raise(foldl((product, x) => product * x, 1, xs), 1 / length(xs));
 
// harmonicMean :: [Number] -> Number
const harmonicMean = xs =>
length(xs) / foldl((invSum, n) => invSum + (1 / n), 0, xs);
 
// GENERIC FUNCTIONS ------------------------------------------------------
 
// A list of functions applied to a list of arguments
// <*> :: [(a -> b)] -> [a] -> [b]
const ap = (fs, xs) => //
[].concat.apply([], fs.map(f => //
[].concat.apply([], xs.map(x => [f(x)]))));
 
// foldl :: (b -> a -> b) -> b -> [a] -> b
const foldl = (f, a, xs) => xs.reduce(f, a);
 
// length :: [a] -> Int
const length = xs => xs.length;
 
// mapFromList :: [(k, v)] -> Dictionary
const mapFromList = kvs =>
foldl((a, [k, v]) =>
(a[(typeof k === 'string' && k) || show(k)] = v, a), {}, kvs);
 
// raise :: Num -> Int -> Num
const raise = (n, e) => Math.pow(n, e);
 
// show :: a -> String
// show :: a -> Int -> String
const show = (...x) =>
JSON.stringify.apply(
null, x.length > 1 ? [x[0], null, x[1]] : x
);
 
// zip :: [a] -> [b] -> [(a,b)]
const zip = (xs, ys) =>
xs.slice(0, Math.min(xs.length, ys.length))
.map((x, i) => [x, ys[i]]);
 
// TEST -------------------------------------------------------------------
// mean :: Dictionary
const mean = mapFromList(zip(
['Arithmetic', 'Geometric', 'Harmonic'],
ap([arithmeticMean, geometricMean, harmonicMean], [
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
])
));
 
return show({
values: mean,
test: `is A >= G >= H ? ${mean.Arithmetic >= mean.Geometric &&
mean.Geometric >= mean.Harmonic ? "yes" : "no"}`
}, 2);
})();</syntaxhighlight>
{{Out}}
<syntaxhighlight lang="javascript">{
"values": {
"Arithmetic": 5.5,
"Geometric": 4.528728688116765,
"Harmonic": 3.414171521474055
},
"test": "is A >= G >= H ? yes"
}</syntaxhighlight>
 
=={{header|jq}}==
<langsyntaxhighlight lang="jq">def amean: add/length;
 
def logProduct: map(log) | add;
Line 1,350 ⟶ 1,943:
| ( $ans[],
"amean > gmean > hmean => \($ans[0] > $ans[1] and $ans[1] > $ans[2] )" )
</syntaxhighlight>
</lang>
{{Out}}
<pre>5.5
Line 1,360 ⟶ 1,953:
Julia has a `mean` function to compute the arithmetic mean of a collections
of numbers. We can redefine it as follows.
<langsyntaxhighlight Julialang="julia">amean(A) = sum(A)/length(A)
 
gmean(A) = prod(A)^(1/length(A))
 
hmean(A) = length(A)/sum(1./A)</langsyntaxhighlight>
{{Out}}
<pre>julia> map(f-> f(1:10), [amean, gmean, hmean])
Line 1,375 ⟶ 1,968:
 
=={{header|K}}==
<syntaxhighlight lang="k">
<lang K>
am:{(+/x)%#x}
gm:{(*/x)^(%#x)}
Line 1,382 ⟶ 1,975:
{(am x;gm x;hm x)} 1+!10
5.5 4.528729 3.414172
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">import kotlin.math.round
<lang kotlin>fun Collection<Double>.geometricMean() =
import kotlin.math.pow
if (isEmpty())
Double.NaN
else Math.pow(reduce { n1, n2 -> n1 * n2 }, 1.0 / size)
 
fun Collection<Double>.geometricMean() =
if (isEmpty()) Double.NaN
else (reduce { n1, n2 -> n1 * n2 }).pow(1.0 / size)
fun Collection<Double>.harmonicMean() =
if (isEmpty() || contains(0.0)) Double.NaN
else size / fold(0.0) { n1, n2 -> Doublen1 + 1.NaN0 / n2 }
else
size / reduce { n1, n2 -> n1 + 1.0 / n2 }
 
fun mainDouble.toFixed(argslen: Array<String>Int = 6) {=
round(this * 10.0.pow(len)) / 10.0.pow(len)
fun main() {
val list = listOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
val a = list.average() // arithmetic mean
val g = list.geometricMean()
val h = list.harmonicMean()
println("A = %f$a G = %f${g.toFixed()} H = %f"${h.formattoFixed(a, g, h)}")
println("A >= G is %b${a >= g}, G >= H is %b".format( a >= g, ${g >= h)}")
require(a >= g && g >=in h..a)
}</langsyntaxhighlight>
{{out}}
<pre>A = 5.500000 G = 4.528729 H = 3.414172
Line 1,410 ⟶ 2,006:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define arithmetic_mean(a::staticarray)::decimal => {
//sum of the list divided by its length
return (with e in #a sum #e) / decimal(#a->size)
Line 1,427 ⟶ 2,023:
arithmetic_mean(generateSeries(1,10)->asStaticArray)
geometric_mean(generateSeries(1,10)->asStaticArray)
harmonic_mean(generateSeries(1,10)->asStaticArray)</langsyntaxhighlight>
 
{{out}}
Line 1,435 ⟶ 2,031:
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">for i = 1 to 10
a = a + i
next
Line 1,460 ⟶ 2,056:
print "False"
end if
</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to compute_means :count
local "sum
make "sum 0
Line 1,484 ⟶ 2,081:
print sentence [Geometric mean is] item 2 :means
print sentence [Harmonic mean is] item 3 :means
bye</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight 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}
Line 1,498 ⟶ 2,095:
h = pymean(nums, function(n) return 1/n end, function(n) return 1/n end)
print(a, g, h)
assert(a >= g and g >= h)</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Dimension(m,0) is the base (lower bound) for each dimension in an array, and can be 0 or 1.
Len(a) or len(M()) return length of a pointer to array and an array, as number of array elements.
For one dimension arrays len() is equal to Dimension(m(),1) where 1 is the first dimension
Dim A(10,10) : Print Len(A())=100
 
 
 
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
sum=lambda -> {
Read m as array
if len(m)=0 then =0 : exit
sum=Array(m, Dimension(m,0))
If len(m)=1 then =sum : exit
k=each(m,2,-1)
While k {
sum+=Array(k)
}
=sum
}
mean=lambda sum (a as array) ->{
=sum(a)/len(a)
}
prod=lambda -> {
m=array
if len(m)=0 then =0 : exit
prod=Array(m, Dimension(m,0))
If len(m)=1 then =prod : exit
k=each(m,2,-1)
While k {
prod*=Array(k)
}
=prod
}
geomean=lambda prod (a as array) -> {
=prod(a)^(1/len(a))
}
harmomean=lambda (a as array) -> {
if len(a)=0 then =0 : exit
sum=1/Array(a, Dimension(a,0))
If len(a)=1 then =1/sum : exit
k=each(a,2,-1)
While k {
sum+=1/Array(k)
}
=len(a)/sum
}
Print sum((1,2,3,4,5))=15
Print prod((1,2,3,4,5))=120
Print mean((1,2,3,4,5))==3
\\ use == to apply rounding before comparison
Print geomean((1,2,3,4,5))==2.60517108469735
Print harmomean((1,2,3,4,5))==2.18978102189784
Generator =lambda x=1 ->{=x : x++}
dim a(10)<<Generator()
Print mean(a())==5.5
Print geomean(a())==4.52872868811677
Print harmomean(a())==3.41417152147412
}
CheckIt
</syntaxhighlight>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">x := [ seq( 1 .. 10 ) ];
Means := proc( x )
uses Statistics;
Line 1,510 ⟶ 2,169:
 
is( Arithmeticmean >= Geometricmean and Geometricmean >= Harmonicmean );
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,519 ⟶ 2,178:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Print["{Arithmetic Mean, Geometric Mean, Harmonic Mean} = ",
N@Through[{Mean, GeometricMean, HarmonicMean}[Range@10]]]</langsyntaxhighlight>
{{out}}
<pre>{Arithmetic Mean, Geometric Mean, Harmonic Mean} = {5.5,4.52873,3.41417}</pre>
 
=={{header|MATLAB}}==
<langsyntaxhighlight MATLABlang="matlab">function [A,G,H] = pythagoreanMeans(list)
A = mean(list);
Line 1,531 ⟶ 2,190:
H = harmmean(list);
end</langsyntaxhighlight>
 
A solution that works for both, Matlab and Octave, is this
 
<langsyntaxhighlight MATLABlang="matlab">function [A,G,H] = pythagoreanMeans(list)
A = mean(list); % arithmetic mean
G = exp(mean(log(list))); % geometric mean
H = 1./mean(1./list); % harmonic mean
end</langsyntaxhighlight>
 
Solution:
<langsyntaxhighlight MATLABlang="matlab">>> [A,G,H]=pythagoreanMeans((1:10))
 
A =
Line 1,556 ⟶ 2,215:
H =
 
3.414171521474055</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">/* built-in */
L: makelist(i, i, 1, 10)$
 
mean(L), numer; /* 5.5 */
geometric_mean(L), numer; /* 4.528728688116765 */
harmonic_mean(L), numer; /* 3.414171521474055 */</langsyntaxhighlight>
 
=={{header|min}}==
<syntaxhighlight lang="min">'avg ^A
(dup product 1 rolldown size / pow) ^G
('size keep (1 swap /) (+) map-reduce /) ^H
 
(((1 10)) range (((A) (G) (H))) cleave) => (puts!) foreach</syntaxhighlight>
{{out}}
<pre>5.5
4.528728688116765
3.414171521474055</pre>
 
=={{header|Modula-2}}==
<syntaxhighlight lang="modula2">MODULE PythagoreanMeans;
FROM FormatString IMPORT FormatString;
FROM LongMath IMPORT power;
FROM LongStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
 
PROCEDURE ArithmeticMean(numbers : ARRAY OF LONGREAL) : LONGREAL;
VAR
i,cnt : CARDINAL;
mean : LONGREAL;
BEGIN
mean := 0.0;
cnt := 0;
FOR i:=0 TO HIGH(numbers) DO
mean := mean + numbers[i];
INC(cnt);
END;
RETURN mean / LFLOAT(cnt)
END ArithmeticMean;
 
PROCEDURE GeometricMean(numbers : ARRAY OF LONGREAL) : LONGREAL;
VAR
i,cnt : CARDINAL;
mean : LONGREAL;
BEGIN
mean := 1.0;
cnt := 0;
FOR i:=0 TO HIGH(numbers) DO
mean := mean * numbers[i];
INC(cnt);
END;
RETURN power(mean, 1.0 / LFLOAT(cnt))
END GeometricMean;
 
PROCEDURE HarmonicMean(numbers : ARRAY OF LONGREAL) : LONGREAL;
VAR
i,cnt : CARDINAL;
mean : LONGREAL;
BEGIN
mean := 0.0;
cnt := 0;
FOR i:=0 TO HIGH(numbers) DO
mean := mean + ( 1.0 / numbers[i]);
INC(cnt);
END;
RETURN LFLOAT(cnt) / mean
END HarmonicMean;
 
 
CONST Size = 10;
TYPE DA = ARRAY[1..Size] OF LONGREAL;
 
VAR
buf : ARRAY[0..63] OF CHAR;
array : DA;
arithmetic,geometric,harmonic : LONGREAL;
BEGIN
array := DA{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0};
 
arithmetic := ArithmeticMean(array);
geometric := GeometricMean(array);
harmonic := HarmonicMean(array);
 
WriteString("A = ");
RealToStr(arithmetic, buf);
WriteString(buf);
WriteString(" G = ");
RealToStr(geometric, buf);
WriteString(buf);
WriteString(" H = ");
RealToStr(harmonic, buf);
WriteString(buf);
WriteLn;
 
FormatString("A >= G is %b, G >= H is %b\n", buf, arithmetic >= geometric, geometric >= harmonic);
WriteString(buf);
 
ReadChar
END PythagoreanMeans.</syntaxhighlight>
 
=={{header|MUMPS}}==
 
<langsyntaxhighlight MUMPSlang="mumps">Pyth(n) New a,ii,g,h,x
For ii=1:1:n set x(ii)=ii
;
Line 1,589 ⟶ 2,340:
Pythagorean means for 1..10:
Average = 5.5 >= Geometric 4.528728688116178495 >= harmonic 3.414171521474055006</langsyntaxhighlight>
 
=={{header|NetRexx}}==
{{trans|ooRexx}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,641 ⟶ 2,392:
-- problem here...
return numbers.size / mean
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,648 ⟶ 2,399:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import math, sequtils, futuresugar
 
proc amean(num: seq[float]): float =
sum(num) / float(len(num))
 
proc gmean(num: seq[float]): float =
result = 1
for n in num: result *= n
result = pow(result, 1.0 / float(num.len))
 
proc hmean(num: seq[float]): float =
for n in num: result += 1.0 / n
result = float(num.len) / result
 
proc ameanFunctional(num: seq[float]): float =
sum(num) / float(num.len)
 
proc gmeanFunctional(num: seq[float]): float =
num.foldl(a * b).pow(1.0 / float(num.len))
 
proc hmeanFunctional(num: seq[float]): float =
float(num.len) / sum(num.mapIt(float, 1.0 / it))
 
let numbers = toSeq(1..10).map((x: int) => float(x))
echo amean(numbers), " ", gmean(numbers), " ", hmean(numbers)</langsyntaxhighlight>
{{out}}
<pre>5.5000000000000000e+005 4.5287286881167654e+00528728688116765 3.4141715214740551e+00414171521474055</pre>
 
=={{header|Oberon-2}}==
Oxford Oberon-2
<langsyntaxhighlight lang="oberon2">
MODULE PythMean;
IMPORT Out, ML := MathL;
Line 1,714 ⟶ 2,465:
END PythMean.
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,721 ⟶ 2,472:
H(1 .. 10): 3.41417152147
</pre>
 
=={{header|Objeck}}==
{{trans|Java}}
<langsyntaxhighlight lang="objeck">class PythagMeans {
function : Main(args : String[]) ~ Nil {
array := [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
Line 1,769 ⟶ 2,521:
return numbers->Size() / mean;
}
}</langsyntaxhighlight>
 
Output:
Line 1,781 ⟶ 2,533:
The three means in one function
 
<langsyntaxhighlight lang="ocaml">let means v =
let n = Array.length v
and a = ref 0.0
Line 1,793 ⟶ 2,545:
let nn = float_of_int n in
(!a /. nn, !b ** (1.0/.nn), nn /. !c)
;;</langsyntaxhighlight>
 
{{out}}
Line 1,801 ⟶ 2,553:
Another implementation using <code>[http://caml.inria.fr/pub/docs/manual-ocaml/libref/Array.html#VALfold_left Array.fold_left]</code> instead of a '''for''' loop:
 
<langsyntaxhighlight lang="ocaml">let means v =
let (a, b, c) =
Array.fold_left
Line 1,809 ⟶ 2,561:
let n = float_of_int (Array.length v) in
(a /. n, b ** (1./.n), n /. c)
;;</langsyntaxhighlight>
 
=={{header|Octave}}==
<syntaxhighlight lang="octave">
<lang Octave>
A = mean(list); % arithmetic mean
G = mean(list,'g'); % geometric mean
H = mean(list,'a'); % harmonic mean
</syntaxhighlight>
</lang>
 
See also Matlab implementation [[#MATLAB]]
Line 1,822 ⟶ 2,574:
=={{header|Oforth}}==
 
<syntaxhighlight lang="oforth">import: mapping
<lang Oforth>: A(l) l avg ;
 
: G(l) l prod l size inv powf ;
: A ( x )
: H(l) l size l map(#inv) sum / ;
x sum
x size dup ifZero: [ 2drop null ] else: [ >float / ]
;
 
: G( x ) #* x reduce x size inv powf ;
 
: H( x ) x size x map( #inv ) sum / ;
 
: averages
| g |
"Geometric mean :" . G(10 seq) G dup .cr ->g
"Arithmetic mean :" . A(10 seq) A dup . g >= ifTrue: [ " ==> A >= G" .cr ]
"Harmonic mean :" . H(10 seq) H dup . g <= ifTrue: [ " ==> G >= H" .cr ] ;</lang>
;</syntaxhighlight>
 
{{out}}
Line 1,840 ⟶ 2,600:
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">a = .array~of(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
<lang ooRexx>
a = .array~of(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
say "Arithmetic =" arithmeticMean(a)", Geometric =" geometricMean(a)", Harmonic =" harmonicMean(a)
 
Line 1,881 ⟶ 2,640:
return numbers~items / mean
 
::requires rxmath LIBRARY</syntaxhighlight>
{{out}}
</lang>
<pre>Arithmetic = 5.5, Geometric = 4.52872869, Harmonic = 3.41417153</pre>
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
%% helpers
fun {Sum Xs} {FoldL Xs Number.'+' 0.0} end
Line 1,915 ⟶ 2,675:
{Show [A G H]}
A >= G = true
G >= H = true</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
General implementations:
<langsyntaxhighlight lang="parigp">arithmetic(v)={
sum(i=1,#v,v[i])/#v
};
Line 1,930 ⟶ 2,690:
 
v=vector(10,i,i);
[arithmetic(v),geometric(v),harmonic(v)]</langsyntaxhighlight>
 
Specific to the first ''n'' positive integers:
<langsyntaxhighlight lang="parigp">arithmetic_first(n)={
(n+1)/2
};
Line 1,948 ⟶ 2,708:
 
[arithmetic_first(10),geometric_first(10),harmonic_first(10)]
%[1]>=%[2] && %[2] >= %[3]</langsyntaxhighlight>
 
These are, asymptotically, n/2, n/e, and n/log n.
Line 1,956 ⟶ 2,716:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub A
{
my $a = 0;
Line 1,981 ⟶ 2,741:
 
print "A=$a\nG=$g\nH=$h\n";
die "Error" unless $a >= $g and $g >= $h;</langsyntaxhighlight>
 
=={{header|Perl 6}}==
{{works with|Rakudo|2015.12}}
 
<lang Perl6>sub A { ([+] @_) / @_ }
sub G { ([*] @_) ** (1 / @_) }
sub H { @_ / [+] 1 X/ @_ }
 
say "A(1,...,10) = ", A(1..10);
say "G(1,...,10) = ", G(1..10);
say "H(1,...,10) = ", H(1..10);
</lang>
 
{{out}}
<pre>A(1,...,10) = 5.5
G(1,...,10) = 4.52872868811677
H(1,...,10) = 3.41417152147406</pre>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
(note to self: iff should really be a builtin)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<lang Phix>function arithmetic_mean(sequence s)
<span style="color: #008080;">function</span> <span style="color: #000000;">arithmetic_mean</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
return sum(s)/length(s)
<span style="color: #008080;">return</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)/</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function geometric_mean(sequence s)
<span style="color: #008080;">function</span> <span style="color: #000000;">geometric_mean</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
atom p = 1
<span style="color: #008080;">return</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">product</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">),</span><span style="color: #000000;">1</span><span style="color: #0000FF;">/</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">))</span>
for i=1 to length(s) do
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
p *= s[i]
end for
<span style="color: #008080;">function</span> <span style="color: #000000;">harmonic_mean</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
return power(p,1/length(s))
<span style="color: #008080;">return</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)/</span><span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_div</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">))</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function harmonic_mean(sequence s)
<span style="color: #008080;">constant</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">7</span><span style="color: #0000FF;">,</span><span style="color: #000000;">8</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">}</span>
atom rsum = 0
<span style="color: #008080;">constant</span> <span style="color: #000000;">arithmetic</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">arithmetic_mean</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">),</span>
for i=1 to length(s) do
<span style="color: #000000;">geometric</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">geometric_mean</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">),</span>
rsum += 1/s[i]
<span style="color: #000000;">harmonic</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">harmonic_mean</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Arithmetic: %.10g\n"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">arithmetic</span><span style="color: #0000FF;">)</span>
return length(s)/rsum
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Geometric: %.10g\n"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">geometric</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Harmonic: %.10g\n"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">harmonic</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Arithmetic&gt;=Geometric&gt;=Harmonic: %t\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">arithmetic</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">geometric</span> <span style="color: #008080;">and</span> <span style="color: #000000;">geometric</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">harmonic</span><span style="color: #0000FF;">})</span>
function iff(integer condition, object Tval, object Fval)
<!--</syntaxhighlight>-->
if condition then return Tval else return Fval end if
end function
 
constant s = {1,2,3,4,5,6,7,8,9,10}
constant arithmetic = arithmetic_mean(s),
geometric = geometric_mean(s),
harmonic = harmonic_mean(s)
printf(1,"Arithmetic: %.10g\n", arithmetic)
printf(1,"Geometric: %.10g\n", geometric)
printf(1,"Harmonic: %.10g\n", harmonic)
printf(1,"Arithmetic>=Geometric>=Harmonic: %s\n", {iff((arithmetic>=geometric and geometric>=harmonic),"true","false")})</lang>
{{out}}
<pre>
Line 2,043 ⟶ 2,776:
 
=={{header|PHP}}==
<langsyntaxhighlight PHPlang="php"><?php
// Created with PHP 7.0
 
Line 2,072 ⟶ 2,805:
echo "Geometric: " . GeometricMean($values) . "\n";
echo "Harmonic: " . HarmonicMean($values) . "\n";
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,081 ⟶ 2,814:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/math.l")
 
(let (Lst (1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0) Len (length Lst))
Line 2,095 ⟶ 2,828:
(format
(*/ (* 1.0 Len) 1.0 (sum '((N) (*/ 1.0 1.0 N)) Lst))
*Scl ) ) )</langsyntaxhighlight>
{{out}}
<pre>Arithmetic mean: 5.500000
Line 2,102 ⟶ 2,835:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
declare n fixed binary,
(Average, Geometric, Harmonic) float;
Line 2,124 ⟶ 2,857:
if Average < Geometric then put skip list ('Error');
if Geometric < Harmonic then put skip list ('Error');
</syntaxhighlight>
</lang>
Results:
<pre>
Line 2,133 ⟶ 2,866:
 
=={{header|PostScript}}==
<syntaxhighlight lang="text">
/pythamean{
/x exch def
Line 2,156 ⟶ 2,889:
 
10 pythamean
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,166 ⟶ 2,899:
 
{{libheader|initlib}}
<langsyntaxhighlight lang="postscript">
/numbers {[1 10] 1 range}.
/recip {1 exch div}.
Line 2,176 ⟶ 2,909:
% Harmonic mean
numbers dup 0 {recip +} fold exch length exch div
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
<langsyntaxhighlight PowerShelllang="powershell">$A = 0
$LogG = 0
$InvH = 0
Line 2,201 ⟶ 2,934:
 
write-host "Is A >= G ? $($A -ge $G)"
write-host "Is G >= H ? $($G -ge $H)"</langsyntaxhighlight>
 
{{out}}
Line 2,209 ⟶ 2,942:
Is A >= G ? True
Is G >= H ? True</pre>
 
=={{header|Processing}}==
<syntaxhighlight lang="processing">void setup() {
float[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
println("Arithmetic mean: " + arithmeticMean(numbers));
println("Geometric mean: " + geometricMean(numbers));
println("Harmonic mean: " + harmonicMean(numbers));
}
 
float arithmeticMean(float[] nums) {
float mean = 0;
for (float n : nums) {
mean += n;
}
mean = mean / nums.length;
return mean;
}
 
float geometricMean(float[] nums) {
float mean = 1;
for (float n : nums) {
mean *= n;
}
mean = pow(mean, 1.0 / nums.length);
return mean;
}
 
float harmonicMean(float[] nums) {
float mean = 0;
for (float n : nums) {
mean += 1 / n;
}
mean = nums.length / mean;
return mean;
}</syntaxhighlight>
{{out}}
<pre>Arithmetic mean: 5.5
Geometric mean: 4.528729
Harmonic mean: 3.4141712</pre>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure.d ArithmeticMean()
For a = 1 To 10
mean + a
Line 2,236 ⟶ 3,008:
Debug ArithmeticMean()
Debug GeometricMean()
Debug HarmonicMean()</langsyntaxhighlight>
 
=={{header|Python}}==
{{works with|Python|3}}
<langsyntaxhighlight Pythonlang="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
numbers = range(1, 11) # 1..10
a, g, h = amean(numbers), gmean(numbers), hmean(numbers)
print(a, g, h)
assert( a >= g >= h )</syntaxhighlight>
</lang>
 
{{out}}
<pre>5.5 4.52872868812 3.41417152147</pre>
 
These are the same in Python 2 apart from requiring explicit float division (either through <code>float()</code> casts or float literals such as <code>1./n</code>); or better, do a <code>from __future__ import division</code>, which works on Python 2.2+ as well as Python 3, and makes division work consistently like it does in Python 3.
 
=={{header|Quackery}}==
 
Uses <code>root</code> from [[Integer roots#Quackery]].
 
<syntaxhighlight lang="quackery"> [] 10 times [ i^ 1+ join ]
 
say "Arithmetic mean:" sp
0 over witheach +
over size 8 point$ echo$
cr
say " Geometric mean:" sp
1 over witheach *
over size 80 ** * 10 root
10 8 ** 8 point$ echo$
cr
say " Harmonic mean:" sp
dup size dip
[ 0 n->v rot
witheach [ n->v 1/v v+ ] ]
n->v 2swap v/ 8 point$ echo$</syntaxhighlight>
 
{{out}}
 
<pre>Arithmetic mean: 5.5
Geometric mean: 4.52872868
Harmonic mean: 3.41417152
</pre>
 
=={{header|R}}==
Initialise x
<syntaxhighlight lang="r">
<lang R>
x <- 1:10
</syntaxhighlight>
</lang>
Arithmetic mean
<syntaxhighlight lang="r">
<lang R>
a <- sum(x)/length(x)
 
</syntaxhighlight>
</lang>
or
<syntaxhighlight lang="r">
<lang R>
a <- mean(x)
</syntaxhighlight>
</lang>
 
The geometric mean
<syntaxhighlight lang="r">
<lang R>
g <- prod(x)^(1/length(x))
</syntaxhighlight>
</lang>
 
The harmonic mean (no error checking that <math>x_i\ne 0,\text{ } \forall \text{ }i=1\ldots n</math>)
<syntaxhighlight lang="r">
<lang R>
h <- length(x)/sum(1/x)
</syntaxhighlight>
</lang>
 
Then:
 
<syntaxhighlight lang="r">
<lang R>
a > g
</syntaxhighlight>
</lang>
 
and
 
<syntaxhighlight lang="r">
<lang R>
g > h
</syntaxhighlight>
</lang>
 
give both
Line 2,305 ⟶ 3,107:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
Line 2,325 ⟶ 3,127:
(harmonic xs)
(>= (arithmetic xs) (geometric xs) (harmonic xs))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,333 ⟶ 3,135:
#t
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2015.12}}
 
<syntaxhighlight lang="raku" line>sub A { ([+] @_) / @_ }
sub G { ([*] @_) ** (1 / @_) }
sub H { @_ / [+] 1 X/ @_ }
 
say "A(1,...,10) = ", A(1..10);
say "G(1,...,10) = ", G(1..10);
say "H(1,...,10) = ", H(1..10);
</syntaxhighlight>
 
{{out}}
<pre>A(1,...,10) = 5.5
G(1,...,10) = 4.52872868811677
H(1,...,10) = 3.41417152147406</pre>
 
=={{header|REXX}}==
REXX doesn't have a &nbsp; '''POW''' &nbsp; function, so an &nbsp; '''IROOT''' &nbsp; ('''i'''nteger '''root''') &nbsp; function is included here.; &nbsp; it includes an
<br>extra error check if used as a general purpose function that would otherwise yield a complex result.
<br><br>Coding note: &nbsp; while the &nbsp; '''do''' &nbsp; loop flow looks nice, it took a bit of work to get exactly right, &nbsp; and doesn't lend itself to being updated easily.
<langsyntaxhighlight lang="rexx">/*REXX program computes and displays the Pythagorean means [Amean, Gmean, Hmean]. */
numeric digits 20 /*use a little extra for the precision.*/
parse arg n . /*obtain the optional argument from CL.*/
if n=='' then| n=10 ="," then n= 10 /*None specified? Then assumeuse the default.*/
sum= 0; prod= 1; rSum= 0 /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ compute Arithmetic mean. ▒▒▒▒▒▒▒▒▒▒▒▒ /*initialize sum/product/reciprocal sum*/
$=; do a#=1 for n; @.a$=a $ # /*populategenerate list theby arrayappending and# calculateto sumlist.*/
sum=sum + @.a sum = sum + # /*compute the sum of all the elements. */
end prod= prod * # /*acompute the product of all elements. */
Amean=sum/n rSum= rSum + 1/# /*calculatecompute the arithmetic mean. sum of the reciprocals. */
say 'Amean =' Amean end /*display " " " #*/
say ' list ='$ /*display the list of numbers used. */
prod=1 /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ compute Geometric mean. ▒▒▒▒▒▒▒▒▒▒▒▒▒*/
say 'Amean =' sum / n do g=1 for n /*calculate & display arithmetic mean.*/
say 'Gmean =' Iroot(prod, n) prod=prod /* @.g " " /*compute" geometric the product of all" elements. */
if result=="[n/a]" then say '***error***: root' y "can't be even if 1st argument is < 0."
end /*g*/
Gmeansay 'Hmean =Iroot(prod,n)' n / rSum /*calculate the geometric mean. " " " harmonic " */
sayexit 'Gmean0 =' Gmean /*display " " " /*stick a fork in it, we're all done. */
rsum=0 /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ compute Harmonic mean. ▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/
do r=1 for n
rsum=rsum + 1/@.r /*compute the sum of the reciprocals. */
end /*r*/
Hmean=n/rsum /*calculate the harmonic mean. */
say 'Hmean =' Hmean /*display " " " */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Iroot: procedure; parse arg x 1 ox, y 1 oy /*get both args, and also a copy of X&Y*/
if x=0 | x=1 | y=1 then return x /*handle special case of zero and unity*/
if y=0 if y=0 then return 1 then return 1 /* " " " " a zero root.*/
if y=1 if x<0 & y//2==0 then return x '[n/a]' /*indicate result is "not applicable". " " a unity root.*/
if x<0 & y//2==0 then do; sayx= abs(x); y= abs(y); m= y - 1 /*checkuse forthe anabsolute illegalvalue combination.for X and Y. */
oDigs= say '*** error *** digits(from Iroot):'; a= oDigs + 5 /*save original digits; add five saydigs.*/
g= (x+1) / y*2 say 'root' y "can't be even if first/*use argumentthis isas <the 0first guesstimate."; say */
d= 5 return '[n/a]' /*return astart with "not5 applicable"dec digs, string.saves CPU time*/
do until d==a; d= min(d + end d, a) /*keep [↑]going as Y<0 yields adigits complexare numberincreased. */
x=abs(x); y=abs(y); m=y-1 numeric digits d; f= d - 2 /*uselimit thedigits absoluteto value fororiginal digits X+ and Y5. */
digO=digits() og= /*saveuse originala accuracynon─guess (decimalfor digsthe old G (guess)*/
a=digO+5 do forever; gm= g**m /*use an extra five digs keep computing at "the Yth "root. */
g=(x+1) / y**y _= format( (m*g*gm + x)/(y*gm),,f) /*use this asis the firstnitty─gritty guesstimatecalculation. */
d=5 if _=g | _=og then leave /*Startare we close enough yet? with 5 decimal digit accuracy. When the digits is large, */
og= g; /*CPU time is wasted when theg= (1st)_ /*save guess isn't──► closeOG; toset the rootnew guess.*/
end /*forever*/
 
end /*until */
do forever /* ◄════════════════════════════╗ keep plugging as digits are increased. */
d=min(d+d,a) /* ║ limit the digits to original digitss+5.*/
numeric digits d /* ║ keep increasing the dec. digit accuracy*/
old=. /* ║ define the old (value) for 1st compare.*/
/* ║ */
do forever /* ◄──────────────────────┐ ║ keep plugging at the Yth root. */
_=format((m*g**y+x)/y/g**m,,d-2) /* │ ║ this is the nitty─gritty stuff. */
if _=g | _=old then leave /* | ║ are we close enough yet? */
old=g; g=_ /* │ ║ save guess to old); set the new guess.*/
end /*forever ►──────────────────────┘ ║ */
/* ║ */
if d==a then leave /* ║ are we at desired dec. digit accuracy? */
end /*forever ►══════════════════════════╝ */
 
_ g= g * sign(ox); if oy<0 then _g= 1 /_ g /*adjust for original X sign; neg. root*/
numeric digits digO; return _/1 numeric digits oDigs; return g / 1 /*normalize to original decimal digits.*/</langsyntaxhighlight>
'''{{out|output''' |text=&nbsp; when using the default inputsinput:}}
<pre>
list = 1 2 3 4 5 6 7 8 9 10
Amean = 5.5
Gmean = 4.528728695287286881167647622
Hmean = 3.414171534141715214740550062
</pre>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
decimals(8)
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Line 2,430 ⟶ 3,233:
next
return sum
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,436 ⟶ 3,239:
geometric mean = 4.52872869
harmonic mean = 3.41417152
</pre>
 
=={{header|RPL}}==
These words can be used either on vectors or lists.
{{works with|HP|28}}
≪ → array op
≪ array 1 GET 2 array SIZE
'''IF''' DUP2 > '''THEN''' DROP2 '''ELSE FOR''' j array GET op EVAL '''NEXT END'''
≫ ≫ '<span style="color:blue">REDUCE</span>' STO
≪ DUP ≪ + ≫ <span style="color:blue">REDUCE</span> SWAP SIZE /
≫ '<span style="color:blue">AMEAN</span>' STO
≪ DUP ≪ * ≫ <span style="color:blue">REDUCE</span> SWAP SIZE INV ^
≫ '<span style="color:blue">GMEAN</span>' STO
≪ SIZE LAST ≪ INV + ≫ <span style="color:blue">REDUCE</span> /
≫ '<span style="color:blue">HMEAN</span>' STO
 
{ 1 2 3 4 5 6 7 8 9 0 } <span style="color:blue">AMEAN</span>
{ 1 2 3 4 5 6 7 8 9 0 } <span style="color:blue">GMEAN</span>
[ 1 2 3 4 5 6 7 8 9 0 ] <span style="color:blue">HMEAN</span>
{{out}}
<pre>
3: 5.5
2: 4.52872868812
1: 3.41417152147
</pre>
 
=={{header|Ruby}}==
{{works with|Ruby|1.9+}}
<langsyntaxhighlight lang="ruby">class Array
def arithmetic_mean
inject(0.0, :+) / length
Line 2,467 ⟶ 3,297:
p h = (1..10).harmonic_mean
# is h < g < a ??
p g.between?(h, a)</langsyntaxhighlight>
 
{{out}}
Line 2,478 ⟶ 3,308:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">bXsum = 1
for i = 1 to 10
sum = sum + i ' sum of 1 -> 10
Line 2,493 ⟶ 3,323:
print " Harmonic Mean:";harmonic
if (average >= geometric) and (geometric >= harmonic) then print "True" else print "False"</langsyntaxhighlight>
{{out}}
<pre>
Line 2,502 ⟶ 3,332:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn main() {
let mut sum = 0.0;
let mut prod = 1;
Line 2,518 ⟶ 3,348:
 
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,526 ⟶ 3,356:
=={{header|Scala}}==
{{works with|Scala|2.8+}}
<langsyntaxhighlight lang="scala">def arithmeticMean(n: Seq[Int]) = n.sum / n.size.toDouble
def geometricMean(n: Seq[Int]) = math.pow(n.foldLeft(1.0)(_*_), 1.0 / n.size.toDouble)
def harmonicMean(n: Seq[Int]) = n.size / n.map(1.0 / _).sum
Line 2,539 ⟶ 3,369:
println("Harmonic mean " + h)
 
assert(a >= g && g >= h)</langsyntaxhighlight>
{{out}}
<pre>Arithmetic mean 5.5
Line 2,547 ⟶ 3,377:
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^5</math>RS}}
<langsyntaxhighlight lang="scheme">(define (a-mean l)
(/ (apply + l) (length l)))
 
Line 2,569 ⟶ 3,399:
(newline)
(display (>= a g h))
(newline))</langsyntaxhighlight>
{{out}}
<syntaxhighlight lang="text">11/2 >= 4.528728688116765 >= 25200/7381
#t</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
 
Line 2,595 ⟶ 3,425:
writeln("Geometric mean: " <& product ** (1.0 / flt(length(numbers))));
writeln("Harmonic mean: " <& flt(length(numbers)) / reciprocalSum);
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,605 ⟶ 3,435:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="sidef">func A(a) { a.sum / a.len }
func G(a) { a.prod.root(a.len) }
func H(a) { a.len / a.map{1/_}.sum }</langsyntaxhighlight>
 
The same thing, using hyper-operators:
<langsyntaxhighlight lang="sidef">func A(a) { a«+» / a.len }
func G(a) { a«*» ** (1/a.len) }
func H(a) { a.len / (a«/«1 «+») }</langsyntaxhighlight>
 
Calling the functions:
<langsyntaxhighlight lang="sidef">say("A(1,...,10) = ", A(1..10));
say("G(1,...,10) = ", G(1..10));
say("H(1,...,10) = ", H(1..10));</langsyntaxhighlight>
{{out}}
<pre>A(1,...,10) = 5.5
Line 2,628 ⟶ 3,458:
This extends the class Collection, so these three methods can be called over any kind of collection, it is enough the the objects of the collection understand +, *, raisedTo, reciprocal and /.
 
<langsyntaxhighlight lang="smalltalk">Collection extend
[
arithmeticMean
Line 2,654 ⟶ 3,484:
 
((a arithmeticMean) >= (a geometricMean)) displayNl.
((a geometricMean) >= (a harmonicMean)) displayNl.</langsyntaxhighlight>
 
{{out}}
Line 2,662 ⟶ 3,492:
true
true</pre>
 
=={{header|SQL}}==
It may not be possible to calculate a geometric mean in a query, but the other two are easy enough.
<syntaxhighlight lang="sql">
--setup
create table averages (val integer);
insert into averages values (1);
insert into averages values (2);
insert into averages values (3);
insert into averages values (4);
insert into averages values (5);
insert into averages values (6);
insert into averages values (7);
insert into averages values (8);
insert into averages values (9);
insert into averages values (10);
-- calculate means
select
1/avg(1/val) as harm,
avg(val) as arith
from
averages;
</syntaxhighlight>
{{out}}
<pre>
HARM ARITH
---------- ----------
3.41417152 5.5
</pre>
 
=={{header|Stata}}==
The command [http://www.stata.com/help.cgi?ameans ameans] prints the arithmetic, geometric and harmonic means, together with confidence intervals.
<syntaxhighlight lang="text">clear all
set obs 10
gen x=_n
ameans x
 
Variable | Type Obs Mean [95% Conf. Interval]
-------------+---------------------------------------------------------------
x | Arithmetic 10 5.5 3.334149 7.665851
| Geometric 10 4.528729 2.680672 7.650836
| Harmonic 10 3.414172 2.035664 10.57602
-----------------------------------------------------------------------------</syntaxhighlight>
=={{header|Swift}}==
<syntaxhighlight lang="text">
// Utility for easy creation of Double from any Numeric
extension Double {
init(withNum v: any Numeric) {
switch v {
case let ii as any BinaryInteger: self.init(ii)
case let ff as any BinaryFloatingPoint: self.init(ff)
default: self.init()
}
}
}
// Extension for numeric collections
extension Collection where Element: Numeric {
var arithmeticMean: Double {
self.reduce(0.0, {$0 + Double(withNum: $1)})/Double(self.count)
}
var geometricMean: Double {
pow(self.reduce(1.0, {$0 * Double(withNum: $1)}), 1.0/Double(self.count))
}
var harmonicMean: Double {
Double(self.count) / self.reduce(0.0, {$0 + 1.0/Double(withNum:$1)})
}
}
//Usage:
var c: [Int] = (1...10).map {$0}
 
print(c.arithmeticMean)
print(c.geometricMean)
print(c.harmonicMean)
 
// output:
// 5.5
// 4.528728688116765
// 3.414171521474055
</syntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc arithmeticMean list {
set sum 0.0
foreach value $list { set sum [expr {$sum + $value}] }
Line 2,686 ⟶ 3,595:
puts "A10=$A10, G10=$G10, H10=$H10"
if {$A10 >= $G10} { puts "A10 >= G10" }
if {$G10 >= $H10} { puts "G10 >= H10" }</langsyntaxhighlight>
 
{{out}}
Line 2,697 ⟶ 3,606:
=={{header|Ursala}}==
 
<langsyntaxhighlight Ursalalang="ursala">#import std
#import flo
 
Line 2,708 ⟶ 3,617:
#cast %eLbX
 
main = ^(~&,ordered not fleq) <a,g,h></langsyntaxhighlight>
{{out}}
<pre>(
Line 2,717 ⟶ 3,626:
Most valac setups will need "-X -lm" added to the compile command to include the C math library.
 
<langsyntaxhighlight lang="vala">
double arithmetic(int[] list){
double mean;
Line 2,770 ⟶ 3,679:
stdout.printf("Harmonic mean: %s\n", harmonic_mean.to_string());
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,778 ⟶ 3,687:
Harmonic mean: 3.4141715214740551
</pre>
 
=={{header|VBA}}==
Uses Excel VBA.
<syntaxhighlight lang="vb">Private Function arithmetic_mean(s() As Variant) As Double
arithmetic_mean = WorksheetFunction.Average(s)
End Function
Private Function geometric_mean(s() As Variant) As Double
geometric_mean = WorksheetFunction.GeoMean(s)
End Function
Private Function harmonic_mean(s() As Variant) As Double
harmonic_mean = WorksheetFunction.HarMean(s)
End Function
Public Sub pythagorean_means()
Dim s() As Variant
s = [{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}]
Debug.Print "A ="; arithmetic_mean(s)
Debug.Print "G ="; geometric_mean(s)
Debug.Print "H ="; harmonic_mean(s)
End Sub</syntaxhighlight>{{out}}
<pre>A = 5,5
G = 4,52872868811677
H = 3,41417152147406 </pre>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Function arithmetic_mean(arr)
sum = 0
Line 2,808 ⟶ 3,739:
WScript.StdOut.WriteLine geometric_mean(Array(1,2,3,4,5,6,7,8,9,10))
WScript.StdOut.WriteLine harmonic_mean(Array(1,2,3,4,5,6,7,8,9,10))
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,815 ⟶ 3,746:
4.52872868811677
3.41417152147406
</pre>
 
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<syntaxhighlight lang="vbnet">Imports System.Runtime.CompilerServices
 
Module Module1
 
<Extension()>
Function Gmean(n As IEnumerable(Of Double)) As Double
Return Math.Pow(n.Aggregate(Function(s, i) s * i), 1.0 / n.Count())
End Function
 
<Extension()>
Function Hmean(n As IEnumerable(Of Double)) As Double
Return n.Count() / n.Sum(Function(i) 1.0 / i)
End Function
 
Sub Main()
Dim nums = From n In Enumerable.Range(1, 10) Select CDbl(n)
 
Dim a = nums.Average()
Dim g = nums.Gmean()
Dim h = nums.Hmean()
 
Console.WriteLine("Arithmetic mean {0}", a)
Console.WriteLine(" Geometric mean {0}", g)
Console.WriteLine(" Harmonic mean {0}", h)
Debug.Assert(a >= g AndAlso g >= h)
End Sub
 
End Module</syntaxhighlight>
{{out}}
<pre>Arithmetic mean 5.5
Geometric mean 4.52872868811677
Harmonic mean 3.41417152147406</pre>
 
=={{header|V (Vlang)}}==
Updated for Vlang version 0.2.2
<syntaxhighlight lang="go">import math
 
fn main() {
mut sum := 0.0
mut prod :=1.0
mut recip_sum := 0.0
n := 10
for val in 1..(n + 1) {
sum += val
prod *= val
recip_sum = recip_sum + ( 1.0 / val )
}
a := sum / n
g := math.pow( prod, ( 1.0 / f32(n) ) )
h := n / recip_sum
result := 'Arithmetic Mean: ${a:3.2f} \nGeometric Mean: ${g:3.2f}\nHarmonic Mean: ${h:3.2f}'
println( result )
compare := if a >= g && g >= h { "Yes" } else { "Nope" }
println('Is A >= G >= H? $compare')
}</syntaxhighlight>
{{out}}
<pre>Arithmetic Mean: 5.50
Geometric Mean: 4.53
Harmonic Mean: 3.41
Is A >= G >= H? Yes</pre>
 
=={{header|Wren}}==
<syntaxhighlight lang="wren">var rng = 1..10
var count = rng.count
var A = rng.reduce { |acc, x| acc + x }/count
var G = rng.reduce { |prod, x| prod * x}.pow(1/count)
var H = rng.reduce { |acc, x| acc + 1/x}.pow(-1) * count
 
System.print("For the numbers %(rng):")
System.print(" Arithmetic mean = %(A)")
System.print(" Geometric mean = %(G)")
System.print(" Harmonic mean = %(H)")
System.print(" A >= G >= H = %(A >= G && G >= H)")</syntaxhighlight>
 
{{out}}
<pre>
For the numbers 1..10:
Arithmetic mean = 5.5
Geometric mean = 4.5287286881168
Harmonic mean = 3.4141715214741
A >= G >= H = true
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
 
func real Power(X, Y); \X raised to the Y power
Line 2,845 ⟶ 3,865:
Text(0, "ALWAYS DECREASING ORDER
");
]</langsyntaxhighlight>
 
{{out}}
Line 2,856 ⟶ 3,876:
 
=={{header|zkl}}==
<syntaxhighlight lang ="zkl">var ns:=T(1,2,3,4,5,6,7,8,9,10);
ns.sum(0.0)/ns.len(); // Arithmetic mean
ns.reduce('*,1.0).pow(1.0/ns.len()); // Geometric mean
ns.len().toFloat() / ns.reduce(fcn(p,n){ p + 1.0/n },0.0); // Harmonic mean</langsyntaxhighlight>
{{out}}
<pre>
Line 2,866 ⟶ 3,886:
3.41417
</pre>
 
[[Category:Geometry]]
Anonymous user