Averages/Pythagorean means: Difference between revisions

Content added Content deleted
(Added Quackery.)
m (syntax highlighting fixup automation)
Line 25: Line 25:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>F amean(num)
<syntaxhighlight lang=11l>F amean(num)
R sum(num)/Float(num.len)
R sum(num)/Float(num.len)
Line 37: Line 37:
print(amean(numbers))
print(amean(numbers))
print(gmean(numbers))
print(gmean(numbers))
print(hmean(numbers))</lang>
print(hmean(numbers))</syntaxhighlight>


{{out}}
{{out}}
Line 48: Line 48:
=={{header|Action!}}==
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
{{libheader|Action! Tool Kit}}
<lang Action!>INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
<syntaxhighlight lang=Action!>INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit


PROC InverseI(INT a,result)
PROC InverseI(INT a,result)
Line 116: Line 116:
HarmonicMean(a,10,result)
HarmonicMean(a,10,result)
Print(" Harmonic mean=") PrintRE(result)
Print(" Harmonic mean=") PrintRE(result)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Pythagorean_means.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Pythagorean_means.png Screenshot from Atari 8-bit computer]
Line 126: Line 126:


=={{header|ActionScript}}==
=={{header|ActionScript}}==
<lang ActionScript>function arithmeticMean(v:Vector.<Number>):Number
<syntaxhighlight lang=ActionScript>function arithmeticMean(v:Vector.<Number>):Number
{
{
var sum:Number = 0;
var sum:Number = 0;
Line 150: Line 150:
trace("Arithmetic: ", arithmeticMean(list));
trace("Arithmetic: ", arithmeticMean(list));
trace("Geometric: ", geometricMean(list));
trace("Geometric: ", geometricMean(list));
trace("Harmonic: ", harmonicMean(list));</lang>
trace("Harmonic: ", harmonicMean(list));</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==


pythagorean_means.ads:
pythagorean_means.ads:
<lang Ada>package Pythagorean_Means is
<syntaxhighlight lang=Ada>package Pythagorean_Means is
type Set is array (Positive range <>) of Float;
type Set is array (Positive range <>) of Float;
function Arithmetic_Mean (Data : Set) return Float;
function Arithmetic_Mean (Data : Set) return Float;
function Geometric_Mean (Data : Set) return Float;
function Geometric_Mean (Data : Set) return Float;
function Harmonic_Mean (Data : Set) return Float;
function Harmonic_Mean (Data : Set) return Float;
end Pythagorean_Means;</lang>
end Pythagorean_Means;</syntaxhighlight>


pythagorean_means.adb:
pythagorean_means.adb:
<lang Ada>with Ada.Numerics.Generic_Elementary_Functions;
<syntaxhighlight lang=Ada>with Ada.Numerics.Generic_Elementary_Functions;
package body Pythagorean_Means is
package body Pythagorean_Means is
package Math is new Ada.Numerics.Generic_Elementary_Functions (Float);
package Math is new Ada.Numerics.Generic_Elementary_Functions (Float);
Line 195: Line 195:
end Harmonic_Mean;
end Harmonic_Mean;


end Pythagorean_Means;</lang>
end Pythagorean_Means;</syntaxhighlight>


example main.adb:
example main.adb:
<lang Ada>with Ada.Text_IO;
<syntaxhighlight lang=Ada>with Ada.Text_IO;
with Pythagorean_Means;
with Pythagorean_Means;
procedure Main is
procedure Main is
Line 210: Line 210:
Float'Image (Geometric_Mean) & " >= " &
Float'Image (Geometric_Mean) & " >= " &
Float'Image (Harmonic_Mean));
Float'Image (Harmonic_Mean));
end Main;</lang>
end Main;</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 217: Line 217:
{{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]}}
{{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}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - argc and argv implementation dependent}}
<lang algol68>main: (
<syntaxhighlight lang=algol68>main: (
INT count:=0;
INT count:=0;
LONG REAL f, sum:=0, prod:=1, resum:=0;
LONG REAL f, sum:=0, prod:=1, resum:=0;
Line 242: Line 242:
printf(($"Geometric mean = "f(real)l$,prod**(1/count)));
printf(($"Geometric mean = "f(real)l$,prod**(1/count)));
printf(($"Harmonic mean = "f(real)l$,count/resum))
printf(($"Harmonic mean = "f(real)l$,count/resum))
)</lang>
)</syntaxhighlight>
Lunix command:
Lunix command:
a68g Averages_Pythagorean_means.a68 - 1 2 3 4 5 6 7 8 9 10
a68g Averages_Pythagorean_means.a68 - 1 2 3 4 5 6 7 8 9 10
Line 257: Line 257:


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw>begin
<syntaxhighlight lang=algolw>begin
% returns the arithmetic mean of the elements of n from lo to hi %
% returns the arithmetic mean of the elements of n from lo to hi %
real procedure arithmeticMean ( real array n ( * ); integer value lo, hi ) ;
real procedure arithmeticMean ( real array n ( * ); integer value lo, hi ) ;
Line 292: Line 292:
write( "Harmonic mean: ", harmonicMean( v, 1, 10 ) )
write( "Harmonic mean: ", harmonicMean( v, 1, 10 ) )


end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 302: Line 302:
=={{header|Amazing Hopper}}==
=={{header|Amazing Hopper}}==
Think about "talk" programming...
Think about "talk" programming...
<lang Amazing Hopper>
<syntaxhighlight lang=Amazing Hopper>
#include <hopper.h>
#include <hopper.h>


Line 363: Line 363:
stats(HARMEAN)
stats(HARMEAN)
back
back
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 398: Line 398:


=={{header|APL}}==
=={{header|APL}}==
<lang APL>
<syntaxhighlight lang=APL>
arithmetic←{(+/⍵)÷⍴⍵}
arithmetic←{(+/⍵)÷⍴⍵}
geometric←{(×/⍵)*÷⍴⍵}
geometric←{(×/⍵)*÷⍴⍵}
Line 411: Line 411:
4.528728688
4.528728688
harmonic x
harmonic x
3.414171521</lang>
3.414171521</syntaxhighlight>


=={{header|AppleScript}}==
=={{header|AppleScript}}==
{{trans|JavaScript}}
{{trans|JavaScript}}
<lang AppleScript>-- arithmetic_mean :: [Number] -> Number
<syntaxhighlight lang=AppleScript>-- arithmetic_mean :: [Number] -> Number
on arithmetic_mean(xs)
on arithmetic_mean(xs)
Line 515: Line 515:
end script
end script
end if
end if
end mReturn</lang>
end mReturn</syntaxhighlight>
{{Out}}
{{Out}}
<lang AppleScript>{values:{arithmetic:5.5, geometric:4.528728688117, harmonic:3.414171521474},
<syntaxhighlight lang=AppleScript>{values:{arithmetic:5.5, geometric:4.528728688117, harmonic:3.414171521474},
inequalities:{|A >= G|:true}, |G >= H|:true}</lang>
inequalities:{|A >= G|:true}, |G >= H|:true}</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>arithmeticMean: function [arr]->
<syntaxhighlight lang=rebol>arithmeticMean: function [arr]->
average arr
average arr


Line 533: Line 533:
print arithmeticMean 1..10
print arithmeticMean 1..10
print geometricMean 1..10
print geometricMean 1..10
print harmonicMean 1..10</lang>
print harmonicMean 1..10</syntaxhighlight>


{{out}}
{{out}}
Line 542: Line 542:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang autohotkey>A := ArithmeticMean(1, 10)
<syntaxhighlight lang=autohotkey>A := ArithmeticMean(1, 10)
G := GeometricMean(1, 10)
G := GeometricMean(1, 10)
H := HarmonicMean(1, 10)
H := HarmonicMean(1, 10)
Line 582: Line 582:
Sum += 1 / (a + A_Index - 1)
Sum += 1 / (a + A_Index - 1)
Return, n / Sum
Return, n / Sum
}</lang>
}</syntaxhighlight>
Message box shows:
Message box shows:
<pre>
<pre>
Line 592: Line 592:


=={{header|AWK}}==
=={{header|AWK}}==
<lang awk>#!/usr/bin/awk -f
<syntaxhighlight lang=awk>#!/usr/bin/awk -f
{
{
x = $1; # value of 1st column
x = $1; # value of 1st column
Line 605: Line 605:
print "Geometric mean : ",exp(G/N);
print "Geometric mean : ",exp(G/N);
print "Harmonic mean : ",N/H;
print "Harmonic mean : ",N/H;
}</lang>
}</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
The arithmetic and harmonic means use BBC BASIC's built-in array operations; only the geometric mean needs a loop.
The arithmetic and harmonic means use BBC BASIC's built-in array operations; only the geometric mean needs a loop.
<lang bbcbasic> DIM a(9)
<syntaxhighlight lang=bbcbasic> DIM a(9)
a() = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
a() = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
PRINT "Arithmetic mean = " ; FNarithmeticmean(a())
PRINT "Arithmetic mean = " ; FNarithmeticmean(a())
Line 632: Line 632:
b() = 1/a()
b() = 1/a()
= (DIM(a(),1)+1) / SUM(b())
= (DIM(a(),1)+1) / SUM(b())
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Arithmetic mean = 5.5
<pre>Arithmetic mean = 5.5
Line 639: Line 639:


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h>
<syntaxhighlight lang=c>#include <stdio.h>
#include <stdlib.h> // atoi()
#include <stdlib.h> // atoi()
#include <math.h> // pow()
#include <math.h> // pow()
Line 661: Line 661:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
Line 668: Line 668:
{{works with|C sharp|C#|3}}
{{works with|C sharp|C#|3}}


<lang csharp>using System;
<syntaxhighlight lang=csharp>using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics;
Line 701: Line 701:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 709: Line 709:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <vector>
<syntaxhighlight lang=cpp>#include <vector>
#include <iostream>
#include <iostream>
#include <numeric>
#include <numeric>
Line 733: Line 733:
<< geometric_mean << " and the harmonic mean " << harmonic_mean << " !\n" ;
<< geometric_mean << " and the harmonic mean " << harmonic_mean << " !\n" ;
return 0 ;
return 0 ;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>The arithmetic mean is 5.5 , the geometric mean 4.52873 and the harmonic mean 3.41417 !</pre>
<pre>The arithmetic mean is 5.5 , the geometric mean 4.52873 and the harmonic mean 3.41417 !</pre>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang Clojure>(use '[clojure.contrib.math :only (expt)])
<syntaxhighlight lang=Clojure>(use '[clojure.contrib.math :only (expt)])
(defn a-mean [coll]
(defn a-mean [coll]
Line 752: Line 752:
a (a-mean numbers) g (g-mean numbers) h (h-mean numbers)]
a (a-mean numbers) g (g-mean numbers) h (h-mean numbers)]
(println a ">=" g ">=" h)
(println a ">=" g ">=" h)
(>= a g h))</lang>
(>= a g h))</syntaxhighlight>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<lang coffeescript>a = [ 1..10 ]
<syntaxhighlight lang=coffeescript>a = [ 1..10 ]
arithmetic_mean = (a) -> a.reduce(((s, x) -> s + x), 0) / a.length
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))
geometic_mean = (a) -> Math.pow(a.reduce(((s, x) -> s * x), 1), (1 / a.length))
Line 765: Line 765:


console.log "A = ", A, " G = ", G, " H = ", H
console.log "A = ", A, " G = ", G, " H = ", H
console.log "A >= G : ", A >= G, " G >= H : ", G >= H</lang>
console.log "A >= G : ", A >= G, " G >= H : ", G >= H</syntaxhighlight>
{{out}}
{{out}}
<pre>A = 5.5 G = 4.528728688116765 H = 3.414171521474055
<pre>A = 5.5 G = 4.528728688116765 H = 3.414171521474055
Line 771: Line 771:


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun generic-mean (nums reduce-op final-op)
<syntaxhighlight lang=lisp>(defun generic-mean (nums reduce-op final-op)
(funcall final-op (reduce reduce-op nums)))
(funcall final-op (reduce reduce-op nums)))


Line 793: Line 793:
(format t "a-mean ~a~%" a-mean)
(format t "a-mean ~a~%" a-mean)
(format t "g-mean ~a~%" g-mean)
(format t "g-mean ~a~%" g-mean)
(format t "h-mean ~a~%" h-mean)))</lang>
(format t "h-mean ~a~%" h-mean)))</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
The output for the harmonic mean is wrong.
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 {
auto aMean(T)(T data) pure nothrow @nogc {
Line 815: Line 815:
writefln("%(%.19f %)", m);
writefln("%(%.19f %)", m);
assert(m.isSorted);
assert(m.isSorted);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>0.9891573712076470036 4.5287286881167647619 5.5000000000000000000</pre>
<pre>0.9891573712076470036 4.5287286881167647619 5.5000000000000000000</pre>


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang Delphi>program AveragesPythagoreanMeans;
<syntaxhighlight lang=Delphi>program AveragesPythagoreanMeans;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 869: Line 869:
else
else
writeln("Error!");
writeln("Error!");
end.</lang>
end.</syntaxhighlight>


=={{header|E}}==
=={{header|E}}==
Line 875: Line 875:
Given that we're defining all three together, it makes sense to express their regularities:
Given that we're defining all three together, it makes sense to express their regularities:


<lang e>def makeMean(base, include, finish) {
<syntaxhighlight lang=e>def makeMean(base, include, finish) {
return def mean(numbers) {
return def mean(numbers) {
var count := 0
var count := 0
Line 889: Line 889:
def A := makeMean(0, fn b,x { b+x }, fn acc,n { acc / n })
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 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 })</lang>
def H := makeMean(0, fn b,x { b+1/x }, fn acc,n { n / acc })</syntaxhighlight>


<lang e>? A(1..10)
<syntaxhighlight lang=e>? A(1..10)
# value: 5.5
# value: 5.5


Line 898: Line 898:


? H(1..10)
? H(1..10)
# value: 3.414171521474055</lang>
# value: 3.414171521474055</syntaxhighlight>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<syntaxhighlight lang=scheme>
(define (A xs) (// (for/sum ((x xs)) x) (length xs)))
(define (A xs) (// (for/sum ((x xs)) x) (length xs)))


Line 911: Line 911:
(and (>= (A xs) (G xs)) (>= (G xs) (H xs)))
(and (>= (A xs) (G xs)) (>= (G xs) (H xs)))
→ #t
→ #t
</syntaxhighlight>
</lang>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>defmodule Means do
<syntaxhighlight lang=elixir>defmodule Means do
def arithmetic(list) do
def arithmetic(list) do
Enum.sum(list) / length(list)
Enum.sum(list) / length(list)
Line 930: Line 930:
IO.puts "Geometric mean: #{gm = Means.geometric(list)}"
IO.puts "Geometric mean: #{gm = Means.geometric(list)}"
IO.puts "Harmonic mean: #{hm = Means.harmonic(list)}"
IO.puts "Harmonic mean: #{hm = Means.harmonic(list)}"
IO.puts "(#{am} >= #{gm} >= #{hm}) is #{am >= gm and gm >= hm}"</lang>
IO.puts "(#{am} >= #{gm} >= #{hm}) is #{am >= gm and gm >= hm}"</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 941: Line 941:
=={{header|Erlang}}==
=={{header|Erlang}}==


<lang Erlang>%% Author: Abhay Jain <abhay_1303@yahoo.co.in>
<syntaxhighlight lang=Erlang>%% Author: Abhay Jain <abhay_1303@yahoo.co.in>


-module(mean_calculator).
-module(mean_calculator).
Line 975: Line 975:
harmonic_mean(Number, Sum) ->
harmonic_mean(Number, Sum) ->
NewSum = Sum + (1/Number),
NewSum = Sum + (1/Number),
harmonic_mean(Number+1, NewSum). </lang>
harmonic_mean(Number+1, NewSum). </syntaxhighlight>


{{out}}
{{out}}
Line 1,027: Line 1,027:
PRINT("Harmonic mean = ";M)
PRINT("Harmonic mean = ";M)
END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>


=={{header|Euler Math Toolbox}}==
=={{header|Euler Math Toolbox}}==


<lang Euler Math Toolbox>
<syntaxhighlight lang=Euler Math Toolbox>
>function A(x) := mean(x)
>function A(x) := mean(x)
>function G(x) := exp(mean(log(x)))
>function G(x) := exp(mean(log(x)))
Line 1,039: Line 1,039:
4.52872868812
4.52872868812
3.41417152147
3.41417152147
</syntaxhighlight>
</lang>


Alternatively, e.g.,
Alternatively, e.g.,


<lang Euler Math Toolbox>
<syntaxhighlight lang=Euler Math Toolbox>
>function G(x) := prod(x)^(1/length(x))
>function G(x) := prod(x)^(1/length(x))
</syntaxhighlight>
</lang>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>function arithmetic_mean(sequence s)
<syntaxhighlight lang=euphoria>function arithmetic_mean(sequence s)
atom sum
atom sum
if length(s) = 0 then
if length(s) = 0 then
Line 1,099: Line 1,099:
printf(1,"Harmonic: %g\n", harmonic)
printf(1,"Harmonic: %g\n", harmonic)
printf(1,"Arithmetic>=Geometric>=Harmonic: %s\n",
printf(1,"Arithmetic>=Geometric>=Harmonic: %s\n",
{true_or_false(arithmetic>=geometric and geometric>=harmonic)})</lang>
{true_or_false(arithmetic>=geometric and geometric>=harmonic)})</syntaxhighlight>


{{out}}
{{out}}
Line 1,112: Line 1,112:
Use the functions : AVERAGE, GEOMEAN and HARMEAN
Use the functions : AVERAGE, GEOMEAN and HARMEAN


<lang Excel>
<syntaxhighlight lang=Excel>
=AVERAGE(1;2;3;4;5;6;7;8;9;10)
=AVERAGE(1;2;3;4;5;6;7;8;9;10)
=GEOMEAN(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)
=HARMEAN(1;2;3;4;5;6;7;8;9;10)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,125: Line 1,125:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>let P = [1.0; 2.0; 3.0; 4.0; 5.0; 6.0; 7.0; 8.0; 9.0; 10.0]
<syntaxhighlight 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) =
let arithmeticMean (x : float list) =
Line 1,142: Line 1,142:
printfn "Arithmetic Mean: %A" (arithmeticMean P)
printfn "Arithmetic Mean: %A" (arithmeticMean P)
printfn "Geometric Mean: %A" (geometricMean P)
printfn "Geometric Mean: %A" (geometricMean P)
printfn "Harmonic Mean: %A" (harmonicMean P)</lang>
printfn "Harmonic Mean: %A" (harmonicMean P)</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>: a-mean ( seq -- mean )
<syntaxhighlight lang=factor>: a-mean ( seq -- mean )
[ sum ] [ length ] bi / ;
[ sum ] [ length ] bi / ;


Line 1,152: Line 1,152:


: h-mean ( seq -- mean )
: h-mean ( seq -- mean )
[ length ] [ [ recip ] map-sum ] bi / ;</lang>
[ length ] [ [ recip ] map-sum ] bi / ;</syntaxhighlight>


( scratchpad ) 10 [1,b] [ a-mean ] [ g-mean ] [ h-mean ] tri
( scratchpad ) 10 [1,b] [ a-mean ] [ g-mean ] [ h-mean ] tri
Line 1,160: Line 1,160:
=={{header|Fantom}}==
=={{header|Fantom}}==


<lang fantom>
<syntaxhighlight lang=fantom>
class Main
class Main
{
{
Line 1,202: Line 1,202:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>: famean ( faddr n -- f )
<syntaxhighlight lang=forth>: famean ( faddr n -- f )
0e
0e
tuck floats bounds do
tuck floats bounds do
Line 1,231: Line 1,231:
test 10 fhmean fdup f.
test 10 fhmean fdup f.
( A G G H )
( A G G H )
f>= . f>= . \ -1 -1</lang>
f>= . f>= . \ -1 -1</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90}}
{{works with|Fortran|90}}
<lang fortran>program Mean
<syntaxhighlight lang=fortran>program Mean


real :: a(10) = (/ (i, i=1,10) /)
real :: a(10) = (/ (i, i=1,10) /)
Line 1,250: Line 1,250:
end if
end if


end program Mean</lang>
end program Mean</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>
<syntaxhighlight lang=freebasic>
' FB 1.05.0 Win64
' FB 1.05.0 Win64


Line 1,294: Line 1,294:
Print "Press any key to quit the program"
Print "Press any key to quit the program"
Sleep
Sleep
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,304: Line 1,304:


=={{header|FunL}}==
=={{header|FunL}}==
<lang funl>import lists.zip
<syntaxhighlight lang=funl>import lists.zip


def
def
Line 1,319: Line 1,319:
println( "$l: $m" + (if m is Rational then " or ${m.doubleValue()}" else '') )
println( "$l: $m" + (if m is Rational then " or ${m.doubleValue()}" else '') )


println( monotone(means, (>=)) )</lang>
println( monotone(means, (>=)) )</syntaxhighlight>


{{out}}
{{out}}
Line 1,332: Line 1,332:
=={{header|Futhark}}==
=={{header|Futhark}}==


<lang Futhark>
<syntaxhighlight lang=Futhark>
fun arithmetic_mean(as: [n]f64): f64 =
fun arithmetic_mean(as: [n]f64): f64 =
reduce (+) 0.0 (map (/f64(n)) as)
reduce (+) 0.0 (map (/f64(n)) as)
Line 1,346: Line 1,346:
geometric_mean as,
geometric_mean as,
harmonic_mean as)
harmonic_mean as)
</syntaxhighlight>
</lang>


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap># The first two work with rationals or with floats
<syntaxhighlight 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)
# (but bear in mind that support of floating point is very poor in GAP)
mean := v -> Sum(v) / Length(v);
mean := v -> Sum(v) / Length(v);
Line 1,366: Line 1,366:
# 3.41417
# 3.41417
geomean(v);
geomean(v);
# 4.52873</lang>
# 4.52873</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang=go>package main


import (
import (
Line 1,386: Line 1,386:
fmt.Println("A:", a, "G:", g, "H:", h)
fmt.Println("A:", a, "G:", g, "H:", h)
fmt.Println("A >= G >= H:", a >= g && g >= h)
fmt.Println("A >= G >= H:", a >= g && g >= h)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,395: Line 1,395:
=={{header|Groovy}}==
=={{header|Groovy}}==
Solution:
Solution:
<lang groovy>def arithMean = { list ->
<syntaxhighlight lang=groovy>def arithMean = { list ->
list == null \
list == null \
? null \
? null \
Line 1,417: Line 1,417:
? 0 \
? 0 \
: list.size() / list.collect { 1.0/it }.sum()
: list.size() / list.collect { 1.0/it }.sum()
}</lang>
}</syntaxhighlight>


Test:
Test:
<lang groovy>def list = 1..10
<syntaxhighlight lang=groovy>def list = 1..10
def A = arithMean(list)
def A = arithMean(list)
def G = geomMean(list)
def G = geomMean(list)
Line 1,431: Line 1,431:
G: ${G}
G: ${G}
H: ${H}
H: ${H}
"""</lang>
"""</syntaxhighlight>


{{out}}
{{out}}
Line 1,443: Line 1,443:
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>.
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>.


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


Line 1,453: Line 1,453:
let ms = zipWith ((. flip mean [1..10]). (,)) "agh" [1, 0, -1]
let ms = zipWith ((. flip mean [1..10]). (,)) "agh" [1, 0, -1]
mapM_ (\(t,m) -> putStrLn $ t : ": " ++ show m) ms
mapM_ (\(t,m) -> putStrLn $ t : ": " ++ show m) ms
putStrLn $ " a >= g >= h is " ++ show ((\(_,[a,g,h])-> a>=g && g>=h) (unzip ms))</lang>
putStrLn $ " a >= g >= h is " ++ show ((\(_,[a,g,h])-> a>=g && g>=h) (unzip ms))</syntaxhighlight>


====Three applicatively defined functions====
====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.
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.


<lang haskell>import Data.List (genericLength)
<syntaxhighlight lang=haskell>import Data.List (genericLength)


-- ARITHMETIC, GEOMETRIC AND HARMONIC MEANS ---------------
-- ARITHMETIC, GEOMETRIC AND HARMONIC MEANS ---------------
Line 1,478: Line 1,478:
, mappend "\n A >= G >= H is " $ --
, mappend "\n A >= G >= H is " $ --
(show . and) $ zipWith (>=) xs (tail xs)
(show . and) $ zipWith (>=) xs (tail xs)
]</lang>
]</syntaxhighlight>
{{Out}}
{{Out}}
<pre>("Arithmetic",5.5)("Geometric",4.528728688116765)("Harmonic",3.414171521474055)
<pre>("Arithmetic",5.5)("Geometric",4.528728688116765)("Harmonic",3.414171521474055)
Line 1,485: Line 1,485:


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang HicEst>AGH = ALIAS( A, G, H ) ! named vector elements
<syntaxhighlight lang=HicEst>AGH = ALIAS( A, G, H ) ! named vector elements
AGH = (0, 1, 0)
AGH = (0, 1, 0)
DO i = 1, 10
DO i = 1, 10
Line 1,494: Line 1,494:
AGH = (A/10, G^0.1, 10/H)
AGH = (A/10, G^0.1, 10/H)


WRITE(ClipBoard, Name) AGH, "Result = " // (A>=G) * (G>=H)</lang>
WRITE(ClipBoard, Name) AGH, "Result = " // (A>=G) * (G>=H)</syntaxhighlight>
! A=5.5; G=4.528728688; H=3.414171521; Result = 1;
! A=5.5; G=4.528728688; H=3.414171521; Result = 1;


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang Icon>link numbers # for a/g/h means
<syntaxhighlight lang=Icon>link numbers # for a/g/h means


procedure main()
procedure main()
Line 1,509: Line 1,509:
write(" a >= g >= h is ", if a >= g >= h then "true" else "false")
write(" a >= g >= h is ", if a >= g >= h then "true" else "false")
end
end
</syntaxhighlight>
</lang>


{{libheader|Icon Programming Library}}
{{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:
[http://www.cs.arizona.edu/icon/library/src/procs/numbers.icn numbers:amean, numbers:gmean, and numbers:hmean] are shown below:
<lang Icon>procedure amean(L[]) #: arithmetic mean
<syntaxhighlight lang=Icon>procedure amean(L[]) #: arithmetic mean
local m
local m
if *L = 0 then fail
if *L = 0 then fail
Line 1,542: Line 1,542:
}
}
return *L / m
return *L / m
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 1,553: Line 1,553:


=={{header|IS-BASIC}}==
=={{header|IS-BASIC}}==
<lang IS-BASIC>100 PROGRAM "Averages.bas"
<syntaxhighlight lang=IS-BASIC>100 PROGRAM "Averages.bas"
110 NUMERIC ARR(1 TO 10)
110 NUMERIC ARR(1 TO 10)
120 FOR I=LBOUND(ARR) TO UBOUND(ARR)
120 FOR I=LBOUND(ARR) TO UBOUND(ARR)
Line 1,581: Line 1,581:
360 NEXT
360 NEXT
370 LET HARMONIC=SIZE(A)/T
370 LET HARMONIC=SIZE(A)/T
380 END DEF</lang>
380 END DEF</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
'''Solution:'''
'''Solution:'''
<lang j>amean=: +/ % #
<syntaxhighlight lang=j>amean=: +/ % #
gmean=: # %: */
gmean=: # %: */
hmean=: amean&.:%</lang>
hmean=: amean&.:%</syntaxhighlight>


'''Example Usage:'''
'''Example Usage:'''
<lang j> (amean , gmean , hmean) >: i. 10
<syntaxhighlight lang=j> (amean , gmean , hmean) >: i. 10
5.5 4.528729 3.414172
5.5 4.528729 3.414172
assert 2 >:/\ (amean , gmean , hmean) >: i. 10 NB. check amean >= gmean and gmean >= hmean</lang>
assert 2 >:/\ (amean , gmean , hmean) >: i. 10 NB. check amean >= gmean and gmean >= hmean</syntaxhighlight>


Note that gmean could have instead been defined as mean under logarithm, for example:
Note that gmean could have instead been defined as mean under logarithm, for example:


<lang j>gmean=:amean&.:^.</lang>
<syntaxhighlight lang=j>gmean=:amean&.:^.</syntaxhighlight>


(and this variant should probably be preferred - especially if the argument list is long, to avoid problems with floating point infinity.)
(and this variant should probably be preferred - especially if the argument list is long, to avoid problems with floating point infinity.)


=={{header|Java}}==
=={{header|Java}}==
<lang java>import java.util.Arrays;
<syntaxhighlight lang=java>import java.util.Arrays;
import java.util.List;
import java.util.List;


Line 1,641: Line 1,641:
System.out.format("A >= G is %b, G >= H is %b%n", (arithmetic >= geometric), (geometric >= harmonic));
System.out.format("A >= G is %b, G >= H is %b%n", (arithmetic >= geometric), (geometric >= harmonic));
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>A = 5.500000 G = 4.528729 H = 3.414172
<pre>A = 5.500000 G = 4.528729 H = 3.414172
Line 1,648: Line 1,648:
{{works with|Java|1.8}}
{{works with|Java|1.8}}
We can rewrite the 3 methods using the new JAVA Stream API:
We can rewrite the 3 methods using the new JAVA Stream API:
<lang java>
<syntaxhighlight lang=java>
public static double arithmAverage(double array[]){
public static double arithmAverage(double array[]){
if (array == null ||array.length == 0) {
if (array == null ||array.length == 0) {
Line 1,685: Line 1,685:
}
}
}
}
</lang>
</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==


===ES5===
===ES5===
<lang javascript>(function () {
<syntaxhighlight lang=javascript>(function () {
'use strict';
'use strict';


Line 1,750: Line 1,750:


})();
})();
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
<lang JavaScript>{
<syntaxhighlight lang=JavaScript>{
"values": {
"values": {
"Arithmetic": 5.5,
"Arithmetic": 5.5,
Line 1,760: Line 1,760:
},
},
"test": "is A >= G >= H ? yes"
"test": "is A >= G >= H ? yes"
}</lang>
}</syntaxhighlight>


===ES6===
===ES6===
<lang JavaScript>(() => {
<syntaxhighlight lang=JavaScript>(() => {


// arithmeticMean :: [Number] -> Number
// arithmeticMean :: [Number] -> Number
Line 1,825: Line 1,825:
mean.Geometric >= mean.Harmonic ? "yes" : "no"}`
mean.Geometric >= mean.Harmonic ? "yes" : "no"}`
}, 2);
}, 2);
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<lang JavaScript>{
<syntaxhighlight lang=JavaScript>{
"values": {
"values": {
"Arithmetic": 5.5,
"Arithmetic": 5.5,
Line 1,834: Line 1,834:
},
},
"test": "is A >= G >= H ? yes"
"test": "is A >= G >= H ? yes"
}</lang>
}</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
<lang jq>def amean: add/length;
<syntaxhighlight lang=jq>def amean: add/length;


def logProduct: map(log) | add;
def logProduct: map(log) | add;
Line 1,849: Line 1,849:
| ( $ans[],
| ( $ans[],
"amean > gmean > hmean => \($ans[0] > $ans[1] and $ans[1] > $ans[2] )" )
"amean > gmean > hmean => \($ans[0] > $ans[1] and $ans[1] > $ans[2] )" )
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>5.5
<pre>5.5
Line 1,859: Line 1,859:
Julia has a `mean` function to compute the arithmetic mean of a collections
Julia has a `mean` function to compute the arithmetic mean of a collections
of numbers. We can redefine it as follows.
of numbers. We can redefine it as follows.
<lang Julia>amean(A) = sum(A)/length(A)
<syntaxhighlight lang=Julia>amean(A) = sum(A)/length(A)


gmean(A) = prod(A)^(1/length(A))
gmean(A) = prod(A)^(1/length(A))


hmean(A) = length(A)/sum(1./A)</lang>
hmean(A) = length(A)/sum(1./A)</syntaxhighlight>
{{Out}}
{{Out}}
<pre>julia> map(f-> f(1:10), [amean, gmean, hmean])
<pre>julia> map(f-> f(1:10), [amean, gmean, hmean])
Line 1,874: Line 1,874:


=={{header|K}}==
=={{header|K}}==
<syntaxhighlight lang=K>
<lang K>
am:{(+/x)%#x}
am:{(+/x)%#x}
gm:{(*/x)^(%#x)}
gm:{(*/x)^(%#x)}
Line 1,881: Line 1,881:
{(am x;gm x;hm x)} 1+!10
{(am x;gm x;hm x)} 1+!10
5.5 4.528729 3.414172
5.5 4.528729 3.414172
</syntaxhighlight>
</lang>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang kotlin>import kotlin.math.round
<syntaxhighlight lang=kotlin>import kotlin.math.round
import kotlin.math.pow
import kotlin.math.pow


Line 1,906: Line 1,906:
println("A >= G is ${a >= g}, G >= H is ${g >= h}")
println("A >= G is ${a >= g}, G >= H is ${g >= h}")
require(g in h..a)
require(g in h..a)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>A = 5.500000 G = 4.528729 H = 3.414172
<pre>A = 5.500000 G = 4.528729 H = 3.414172
Line 1,912: Line 1,912:


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>define arithmetic_mean(a::staticarray)::decimal => {
<syntaxhighlight lang=Lasso>define arithmetic_mean(a::staticarray)::decimal => {
//sum of the list divided by its length
//sum of the list divided by its length
return (with e in #a sum #e) / decimal(#a->size)
return (with e in #a sum #e) / decimal(#a->size)
Line 1,929: Line 1,929:
arithmetic_mean(generateSeries(1,10)->asStaticArray)
arithmetic_mean(generateSeries(1,10)->asStaticArray)
geometric_mean(generateSeries(1,10)->asStaticArray)
geometric_mean(generateSeries(1,10)->asStaticArray)
harmonic_mean(generateSeries(1,10)->asStaticArray)</lang>
harmonic_mean(generateSeries(1,10)->asStaticArray)</syntaxhighlight>


{{out}}
{{out}}
Line 1,937: Line 1,937:


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>for i = 1 to 10
<syntaxhighlight lang=lb>for i = 1 to 10
a = a + i
a = a + i
next
next
Line 1,962: Line 1,962:
print "False"
print "False"
end if
end if
</lang>
</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>to compute_means :count
<syntaxhighlight lang=logo>to compute_means :count
local "sum
local "sum
make "sum 0
make "sum 0
Line 1,987: Line 1,987:
print sentence [Geometric mean is] item 2 :means
print sentence [Geometric mean is] item 2 :means
print sentence [Harmonic mean is] item 3 :means
print sentence [Harmonic mean is] item 3 :means
bye</lang>
bye</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>function fsum(f, a, ...) return a and f(a) + fsum(f, ...) or 0 end
<syntaxhighlight 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
function pymean(t, f, finv) return finv(fsum(f, unpack(t)) / #t) end
nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Line 2,001: Line 2,001:
h = pymean(nums, function(n) return 1/n end, function(n) return 1/n end)
h = pymean(nums, function(n) return 1/n end, function(n) return 1/n end)
print(a, g, h)
print(a, g, h)
assert(a >= g and g >= h)</lang>
assert(a >= g and g >= h)</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
Line 2,011: Line 2,011:




<lang M2000 Interpreter>
<syntaxhighlight lang=M2000 Interpreter>
Module CheckIt {
Module CheckIt {
sum=lambda -> {
sum=lambda -> {
Line 2,064: Line 2,064:
}
}
CheckIt
CheckIt
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>x := [ seq( 1 .. 10 ) ];
<syntaxhighlight lang=Maple>x := [ seq( 1 .. 10 ) ];
Means := proc( x )
Means := proc( x )
uses Statistics;
uses Statistics;
Line 2,075: Line 2,075:


is( Arithmeticmean >= Geometricmean and Geometricmean >= Harmonicmean );
is( Arithmeticmean >= Geometricmean and Geometricmean >= Harmonicmean );
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,084: Line 2,084:


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>Print["{Arithmetic Mean, Geometric Mean, Harmonic Mean} = ",
<syntaxhighlight lang=Mathematica>Print["{Arithmetic Mean, Geometric Mean, Harmonic Mean} = ",
N@Through[{Mean, GeometricMean, HarmonicMean}[Range@10]]]</lang>
N@Through[{Mean, GeometricMean, HarmonicMean}[Range@10]]]</syntaxhighlight>
{{out}}
{{out}}
<pre>{Arithmetic Mean, Geometric Mean, Harmonic Mean} = {5.5,4.52873,3.41417}</pre>
<pre>{Arithmetic Mean, Geometric Mean, Harmonic Mean} = {5.5,4.52873,3.41417}</pre>


=={{header|MATLAB}}==
=={{header|MATLAB}}==
<lang MATLAB>function [A,G,H] = pythagoreanMeans(list)
<syntaxhighlight lang=MATLAB>function [A,G,H] = pythagoreanMeans(list)
A = mean(list);
A = mean(list);
Line 2,096: Line 2,096:
H = harmmean(list);
H = harmmean(list);
end</lang>
end</syntaxhighlight>


A solution that works for both, Matlab and Octave, is this
A solution that works for both, Matlab and Octave, is this


<lang MATLAB>function [A,G,H] = pythagoreanMeans(list)
<syntaxhighlight lang=MATLAB>function [A,G,H] = pythagoreanMeans(list)
A = mean(list); % arithmetic mean
A = mean(list); % arithmetic mean
G = exp(mean(log(list))); % geometric mean
G = exp(mean(log(list))); % geometric mean
H = 1./mean(1./list); % harmonic mean
H = 1./mean(1./list); % harmonic mean
end</lang>
end</syntaxhighlight>


Solution:
Solution:
<lang MATLAB>>> [A,G,H]=pythagoreanMeans((1:10))
<syntaxhighlight lang=MATLAB>>> [A,G,H]=pythagoreanMeans((1:10))


A =
A =
Line 2,121: Line 2,121:
H =
H =


3.414171521474055</lang>
3.414171521474055</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>/* built-in */
<syntaxhighlight lang=maxima>/* built-in */
L: makelist(i, i, 1, 10)$
L: makelist(i, i, 1, 10)$


mean(L), numer; /* 5.5 */
mean(L), numer; /* 5.5 */
geometric_mean(L), numer; /* 4.528728688116765 */
geometric_mean(L), numer; /* 4.528728688116765 */
harmonic_mean(L), numer; /* 3.414171521474055 */</lang>
harmonic_mean(L), numer; /* 3.414171521474055 */</syntaxhighlight>


=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>MODULE PythagoreanMeans;
<syntaxhighlight lang=modula2>MODULE PythagoreanMeans;
FROM FormatString IMPORT FormatString;
FROM FormatString IMPORT FormatString;
FROM LongMath IMPORT power;
FROM LongMath IMPORT power;
Line 2,210: Line 2,210:


ReadChar
ReadChar
END PythagoreanMeans.</lang>
END PythagoreanMeans.</syntaxhighlight>


=={{header|MUMPS}}==
=={{header|MUMPS}}==


<lang MUMPS>Pyth(n) New a,ii,g,h,x
<syntaxhighlight lang=MUMPS>Pyth(n) New a,ii,g,h,x
For ii=1:1:n set x(ii)=ii
For ii=1:1:n set x(ii)=ii
;
;
Line 2,235: Line 2,235:
Pythagorean means for 1..10:
Pythagorean means for 1..10:
Average = 5.5 >= Geometric 4.528728688116178495 >= harmonic 3.414171521474055006</lang>
Average = 5.5 >= Geometric 4.528728688116178495 >= harmonic 3.414171521474055006</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
{{trans|ooRexx}}
{{trans|ooRexx}}
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang=NetRexx>/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 2,287: Line 2,287:
-- problem here...
-- problem here...
return numbers.size / mean
return numbers.size / mean
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,294: Line 2,294:


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import math, sequtils, sugar
<syntaxhighlight lang=nim>import math, sequtils, sugar
proc amean(num: seq[float]): float =
proc amean(num: seq[float]): float =
Line 2,318: Line 2,318:
let numbers = toSeq(1..10).map((x: int) => float(x))
let numbers = toSeq(1..10).map((x: int) => float(x))
echo amean(numbers), " ", gmean(numbers), " ", hmean(numbers)</lang>
echo amean(numbers), " ", gmean(numbers), " ", hmean(numbers)</syntaxhighlight>
{{out}}
{{out}}
<pre>5.5 4.528728688116765 3.414171521474055</pre>
<pre>5.5 4.528728688116765 3.414171521474055</pre>
Line 2,324: Line 2,324:
=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
Oxford Oberon-2
Oxford Oberon-2
<lang oberon2>
<syntaxhighlight lang=oberon2>
MODULE PythMean;
MODULE PythMean;
IMPORT Out, ML := MathL;
IMPORT Out, ML := MathL;
Line 2,360: Line 2,360:
END PythMean.
END PythMean.


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,370: Line 2,370:
=={{header|Objeck}}==
=={{header|Objeck}}==
{{trans|Java}}
{{trans|Java}}
<lang objeck>class PythagMeans {
<syntaxhighlight lang=objeck>class PythagMeans {
function : Main(args : String[]) ~ Nil {
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];
array := [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
Line 2,416: Line 2,416:
return numbers->Size() / mean;
return numbers->Size() / mean;
}
}
}</lang>
}</syntaxhighlight>


Output:
Output:
Line 2,428: Line 2,428:
The three means in one function
The three means in one function


<lang ocaml>let means v =
<syntaxhighlight lang=ocaml>let means v =
let n = Array.length v
let n = Array.length v
and a = ref 0.0
and a = ref 0.0
Line 2,440: Line 2,440:
let nn = float_of_int n in
let nn = float_of_int n in
(!a /. nn, !b ** (1.0/.nn), nn /. !c)
(!a /. nn, !b ** (1.0/.nn), nn /. !c)
;;</lang>
;;</syntaxhighlight>


{{out}}
{{out}}
Line 2,448: Line 2,448:
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:
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:


<lang ocaml>let means v =
<syntaxhighlight lang=ocaml>let means v =
let (a, b, c) =
let (a, b, c) =
Array.fold_left
Array.fold_left
Line 2,456: Line 2,456:
let n = float_of_int (Array.length v) in
let n = float_of_int (Array.length v) in
(a /. n, b ** (1./.n), n /. c)
(a /. n, b ** (1./.n), n /. c)
;;</lang>
;;</syntaxhighlight>


=={{header|Octave}}==
=={{header|Octave}}==
<lang Octave>
<syntaxhighlight lang=Octave>
A = mean(list); % arithmetic mean
A = mean(list); % arithmetic mean
G = mean(list,'g'); % geometric mean
G = mean(list,'g'); % geometric mean
H = mean(list,'a'); % harmonic mean
H = mean(list,'a'); % harmonic mean
</syntaxhighlight>
</lang>


See also Matlab implementation [[#MATLAB]]
See also Matlab implementation [[#MATLAB]]
Line 2,469: Line 2,469:
=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>import: mapping
<syntaxhighlight lang=Oforth>import: mapping


: A ( x )
: A ( x )
Line 2,485: Line 2,485:
"Arithmetic mean :" . 10 seq A dup . g >= ifTrue: [ " ==> A >= G" .cr ]
"Arithmetic mean :" . 10 seq A dup . g >= ifTrue: [ " ==> A >= G" .cr ]
"Harmonic mean :" . 10 seq H dup . g <= ifTrue: [ " ==> G >= H" .cr ]
"Harmonic mean :" . 10 seq H dup . g <= ifTrue: [ " ==> G >= H" .cr ]
;</lang>
;</syntaxhighlight>


{{out}}
{{out}}
Line 2,495: Line 2,495:


=={{header|ooRexx}}==
=={{header|ooRexx}}==
<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)
<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)
say "Arithmetic =" arithmeticMean(a)", Geometric =" geometricMean(a)", Harmonic =" harmonicMean(a)
say "Arithmetic =" arithmeticMean(a)", Geometric =" geometricMean(a)", Harmonic =" harmonicMean(a)


Line 2,535: Line 2,535:
return numbers~items / mean
return numbers~items / mean


::requires rxmath LIBRARY</lang>
::requires rxmath LIBRARY</syntaxhighlight>
{{out}}
{{out}}
<pre>Arithmetic = 5.5, Geometric = 4.52872869, Harmonic = 3.41417153</pre>
<pre>Arithmetic = 5.5, Geometric = 4.52872869, Harmonic = 3.41417153</pre>


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang=oz>declare
%% helpers
%% helpers
fun {Sum Xs} {FoldL Xs Number.'+' 0.0} end
fun {Sum Xs} {FoldL Xs Number.'+' 0.0} end
Line 2,570: Line 2,570:
{Show [A G H]}
{Show [A G H]}
A >= G = true
A >= G = true
G >= H = true</lang>
G >= H = true</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
General implementations:
General implementations:
<lang parigp>arithmetic(v)={
<syntaxhighlight lang=parigp>arithmetic(v)={
sum(i=1,#v,v[i])/#v
sum(i=1,#v,v[i])/#v
};
};
Line 2,585: Line 2,585:


v=vector(10,i,i);
v=vector(10,i,i);
[arithmetic(v),geometric(v),harmonic(v)]</lang>
[arithmetic(v),geometric(v),harmonic(v)]</syntaxhighlight>


Specific to the first ''n'' positive integers:
Specific to the first ''n'' positive integers:
<lang parigp>arithmetic_first(n)={
<syntaxhighlight lang=parigp>arithmetic_first(n)={
(n+1)/2
(n+1)/2
};
};
Line 2,603: Line 2,603:


[arithmetic_first(10),geometric_first(10),harmonic_first(10)]
[arithmetic_first(10),geometric_first(10),harmonic_first(10)]
%[1]>=%[2] && %[2] >= %[3]</lang>
%[1]>=%[2] && %[2] >= %[3]</syntaxhighlight>


These are, asymptotically, n/2, n/e, and n/log n.
These are, asymptotically, n/2, n/e, and n/log n.
Line 2,611: Line 2,611:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>sub A
<syntaxhighlight lang=perl>sub A
{
{
my $a = 0;
my $a = 0;
Line 2,636: Line 2,636:


print "A=$a\nG=$g\nH=$h\n";
print "A=$a\nG=$g\nH=$h\n";
die "Error" unless $a >= $g and $g >= $h;</lang>
die "Error" unless $a >= $g and $g >= $h;</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang=Phix>(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
<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>
Line 2,661: Line 2,661:
<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;">"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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,671: Line 2,671:


=={{header|PHP}}==
=={{header|PHP}}==
<lang PHP><?php
<syntaxhighlight lang=PHP><?php
// Created with PHP 7.0
// Created with PHP 7.0


Line 2,700: Line 2,700:
echo "Geometric: " . GeometricMean($values) . "\n";
echo "Geometric: " . GeometricMean($values) . "\n";
echo "Harmonic: " . HarmonicMean($values) . "\n";
echo "Harmonic: " . HarmonicMean($values) . "\n";
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,709: Line 2,709:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(load "@lib/math.l")
<syntaxhighlight lang=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))
(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,723: Line 2,723:
(format
(format
(*/ (* 1.0 Len) 1.0 (sum '((N) (*/ 1.0 1.0 N)) Lst))
(*/ (* 1.0 Len) 1.0 (sum '((N) (*/ 1.0 1.0 N)) Lst))
*Scl ) ) )</lang>
*Scl ) ) )</syntaxhighlight>
{{out}}
{{out}}
<pre>Arithmetic mean: 5.500000
<pre>Arithmetic mean: 5.500000
Line 2,730: Line 2,730:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang PL/I>
<syntaxhighlight lang=PL/I>
declare n fixed binary,
declare n fixed binary,
(Average, Geometric, Harmonic) float;
(Average, Geometric, Harmonic) float;
Line 2,752: Line 2,752:
if Average < Geometric then put skip list ('Error');
if Average < Geometric then put skip list ('Error');
if Geometric < Harmonic then put skip list ('Error');
if Geometric < Harmonic then put skip list ('Error');
</syntaxhighlight>
</lang>
Results:
Results:
<pre>
<pre>
Line 2,784: Line 2,784:


10 pythamean
10 pythamean
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,794: Line 2,794:


{{libheader|initlib}}
{{libheader|initlib}}
<lang postscript>
<syntaxhighlight lang=postscript>
/numbers {[1 10] 1 range}.
/numbers {[1 10] 1 range}.
/recip {1 exch div}.
/recip {1 exch div}.
Line 2,804: Line 2,804:
% Harmonic mean
% Harmonic mean
numbers dup 0 {recip +} fold exch length exch div
numbers dup 0 {recip +} fold exch length exch div
</syntaxhighlight>
</lang>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang PowerShell>$A = 0
<syntaxhighlight lang=PowerShell>$A = 0
$LogG = 0
$LogG = 0
$InvH = 0
$InvH = 0
Line 2,829: Line 2,829:


write-host "Is A >= G ? $($A -ge $G)"
write-host "Is A >= G ? $($A -ge $G)"
write-host "Is G >= H ? $($G -ge $H)"</lang>
write-host "Is G >= H ? $($G -ge $H)"</syntaxhighlight>


{{out}}
{{out}}
Line 2,839: Line 2,839:


=={{header|Processing}}==
=={{header|Processing}}==
<lang Processing>void setup() {
<syntaxhighlight lang=Processing>void setup() {
float[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
float[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
println("Arithmetic mean: " + arithmeticMean(numbers));
println("Arithmetic mean: " + arithmeticMean(numbers));
Line 2,871: Line 2,871:
mean = nums.length / mean;
mean = nums.length / mean;
return mean;
return mean;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Arithmetic mean: 5.5
<pre>Arithmetic mean: 5.5
Line 2,878: Line 2,878:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>Procedure.d ArithmeticMean()
<syntaxhighlight lang=PureBasic>Procedure.d ArithmeticMean()
For a = 1 To 10
For a = 1 To 10
mean + a
mean + a
Line 2,903: Line 2,903:
Debug ArithmeticMean()
Debug ArithmeticMean()
Debug GeometricMean()
Debug GeometricMean()
Debug HarmonicMean()</lang>
Debug HarmonicMean()</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
{{works with|Python|3}}
{{works with|Python|3}}
<lang Python>from operator import mul
<syntaxhighlight lang=Python>from operator import mul
from functools import reduce
from functools import reduce


Line 2,926: Line 2,926:
a, g, h = amean(numbers), gmean(numbers), hmean(numbers)
a, g, h = amean(numbers), gmean(numbers), hmean(numbers)
print(a, g, h)
print(a, g, h)
assert a >= g >= h</lang>
assert a >= g >= h</syntaxhighlight>
{{out}}
{{out}}
<pre>5.5 4.52872868812 3.41417152147</pre>
<pre>5.5 4.52872868812 3.41417152147</pre>
Line 2,936: Line 2,936:
Uses <code>root</code> from [[Integer roots#Quackery]].
Uses <code>root</code> from [[Integer roots#Quackery]].


<lang Quackery> [] 10 times [ i^ 1+ join ]
<syntaxhighlight lang=Quackery> [] 10 times [ i^ 1+ join ]


say "Arithmetic mean:" sp
say "Arithmetic mean:" sp
Line 2,951: Line 2,951:
[ 0 n->v rot
[ 0 n->v rot
witheach [ n->v 1/v v+ ] ]
witheach [ n->v 1/v v+ ] ]
n->v 2swap v/ 8 point$ echo$</lang>
n->v 2swap v/ 8 point$ echo$</syntaxhighlight>


{{out}}
{{out}}
Line 2,962: Line 2,962:
=={{header|R}}==
=={{header|R}}==
Initialise x
Initialise x
<syntaxhighlight lang=R>
<lang R>
x <- 1:10
x <- 1:10
</syntaxhighlight>
</lang>
Arithmetic mean
Arithmetic mean
<syntaxhighlight lang=R>
<lang R>
a <- sum(x)/length(x)
a <- sum(x)/length(x)


</syntaxhighlight>
</lang>
or
or
<syntaxhighlight lang=R>
<lang R>
a <- mean(x)
a <- mean(x)
</syntaxhighlight>
</lang>


The geometric mean
The geometric mean
<syntaxhighlight lang=R>
<lang R>
g <- prod(x)^(1/length(x))
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>)
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)
h <- length(x)/sum(1/x)
</syntaxhighlight>
</lang>


Then:
Then:


<syntaxhighlight lang=R>
<lang R>
a > g
a > g
</syntaxhighlight>
</lang>


and
and


<syntaxhighlight lang=R>
<lang R>
g > h
g > h
</syntaxhighlight>
</lang>


give both
give both
Line 3,002: Line 3,002:


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>
<syntaxhighlight lang=racket>
#lang racket
#lang racket
Line 3,022: Line 3,022:
(harmonic xs)
(harmonic xs)
(>= (arithmetic xs) (geometric xs) (harmonic xs))
(>= (arithmetic xs) (geometric xs) (harmonic xs))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,035: Line 3,035:
{{works with|Rakudo|2015.12}}
{{works with|Rakudo|2015.12}}


<lang perl6>sub A { ([+] @_) / @_ }
<syntaxhighlight lang=perl6>sub A { ([+] @_) / @_ }
sub G { ([*] @_) ** (1 / @_) }
sub G { ([*] @_) ** (1 / @_) }
sub H { @_ / [+] 1 X/ @_ }
sub H { @_ / [+] 1 X/ @_ }
Line 3,042: Line 3,042:
say "G(1,...,10) = ", G(1..10);
say "G(1,...,10) = ", G(1..10);
say "H(1,...,10) = ", H(1..10);
say "H(1,...,10) = ", H(1..10);
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,052: Line 3,052:
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
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>extra error check if used as a general purpose function that would otherwise yield a complex result.
<lang rexx>/*REXX program computes and displays the Pythagorean means [Amean, Gmean, Hmean]. */
<syntaxhighlight lang=rexx>/*REXX program computes and displays the Pythagorean means [Amean, Gmean, Hmean]. */
numeric digits 20 /*use a little extra for the precision.*/
numeric digits 20 /*use a little extra for the precision.*/
parse arg n . /*obtain the optional argument from CL.*/
parse arg n . /*obtain the optional argument from CL.*/
Line 3,088: Line 3,088:


g= g * sign(ox); if oy<0 then g= 1 / g /*adjust for original X sign; neg. root*/
g= g * sign(ox); if oy<0 then g= 1 / g /*adjust for original X sign; neg. root*/
numeric digits oDigs; return g / 1 /*normalize to original decimal digits.*/</lang>
numeric digits oDigs; return g / 1 /*normalize to original decimal digits.*/</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
{{out|output|text=&nbsp; when using the default input:}}
<pre>
<pre>
Line 3,098: Line 3,098:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang=ring>
decimals(8)
decimals(8)
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Line 3,128: Line 3,128:
next
next
return sum
return sum
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 3,138: Line 3,138:
=={{header|Ruby}}==
=={{header|Ruby}}==
{{works with|Ruby|1.9+}}
{{works with|Ruby|1.9+}}
<lang ruby>class Array
<syntaxhighlight lang=ruby>class Array
def arithmetic_mean
def arithmetic_mean
inject(0.0, :+) / length
inject(0.0, :+) / length
Line 3,165: Line 3,165:
p h = (1..10).harmonic_mean
p h = (1..10).harmonic_mean
# is h < g < a ??
# is h < g < a ??
p g.between?(h, a)</lang>
p g.between?(h, a)</syntaxhighlight>


{{out}}
{{out}}
Line 3,176: Line 3,176:


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>bXsum = 1
<syntaxhighlight lang=runbasic>bXsum = 1
for i = 1 to 10
for i = 1 to 10
sum = sum + i ' sum of 1 -> 10
sum = sum + i ' sum of 1 -> 10
Line 3,191: Line 3,191:
print " Harmonic Mean:";harmonic
print " Harmonic Mean:";harmonic
if (average >= geometric) and (geometric >= harmonic) then print "True" else print "False"</lang>
if (average >= geometric) and (geometric >= harmonic) then print "True" else print "False"</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,200: Line 3,200:


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>fn main() {
<syntaxhighlight lang=rust>fn main() {
let mut sum = 0.0;
let mut sum = 0.0;
let mut prod = 1;
let mut prod = 1;
Line 3,216: Line 3,216:


}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,224: Line 3,224:
=={{header|Scala}}==
=={{header|Scala}}==
{{works with|Scala|2.8+}}
{{works with|Scala|2.8+}}
<lang scala>def arithmeticMean(n: Seq[Int]) = n.sum / n.size.toDouble
<syntaxhighlight 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 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
def harmonicMean(n: Seq[Int]) = n.size / n.map(1.0 / _).sum
Line 3,237: Line 3,237:
println("Harmonic mean " + h)
println("Harmonic mean " + h)


assert(a >= g && g >= h)</lang>
assert(a >= g && g >= h)</syntaxhighlight>
{{out}}
{{out}}
<pre>Arithmetic mean 5.5
<pre>Arithmetic mean 5.5
Line 3,245: Line 3,245:
=={{header|Scheme}}==
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^5</math>RS}}
{{Works with|Scheme|R<math>^5</math>RS}}
<lang scheme>(define (a-mean l)
<syntaxhighlight lang=scheme>(define (a-mean l)
(/ (apply + l) (length l)))
(/ (apply + l) (length l)))


Line 3,267: Line 3,267:
(newline)
(newline)
(display (>= a g h))
(display (>= a g h))
(newline))</lang>
(newline))</syntaxhighlight>
{{out}}
{{out}}
<lang>11/2 >= 4.528728688116765 >= 25200/7381
<lang>11/2 >= 4.528728688116765 >= 25200/7381
#t</lang>
#t</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang=seed7>$ include "seed7_05.s7i";
include "float.s7i";
include "float.s7i";


Line 3,293: Line 3,293:
writeln("Geometric mean: " <& product ** (1.0 / flt(length(numbers))));
writeln("Geometric mean: " <& product ** (1.0 / flt(length(numbers))));
writeln("Harmonic mean: " <& flt(length(numbers)) / reciprocalSum);
writeln("Harmonic mean: " <& flt(length(numbers)) / reciprocalSum);
end func;</lang>
end func;</syntaxhighlight>


{{out}}
{{out}}
Line 3,303: Line 3,303:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang sidef>func A(a) { a.sum / a.len }
<syntaxhighlight lang=sidef>func A(a) { a.sum / a.len }
func G(a) { a.prod.root(a.len) }
func G(a) { a.prod.root(a.len) }
func H(a) { a.len / a.map{1/_}.sum }</lang>
func H(a) { a.len / a.map{1/_}.sum }</syntaxhighlight>


The same thing, using hyper-operators:
The same thing, using hyper-operators:
<lang sidef>func A(a) { a«+» / a.len }
<syntaxhighlight lang=sidef>func A(a) { a«+» / a.len }
func G(a) { a«*» ** (1/a.len) }
func G(a) { a«*» ** (1/a.len) }
func H(a) { a.len / (a«/«1 «+») }</lang>
func H(a) { a.len / (a«/«1 «+») }</syntaxhighlight>


Calling the functions:
Calling the functions:
<lang sidef>say("A(1,...,10) = ", A(1..10));
<syntaxhighlight lang=sidef>say("A(1,...,10) = ", A(1..10));
say("G(1,...,10) = ", G(1..10));
say("G(1,...,10) = ", G(1..10));
say("H(1,...,10) = ", H(1..10));</lang>
say("H(1,...,10) = ", H(1..10));</syntaxhighlight>
{{out}}
{{out}}
<pre>A(1,...,10) = 5.5
<pre>A(1,...,10) = 5.5
Line 3,326: Line 3,326:
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 /.
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 /.


<lang smalltalk>Collection extend
<syntaxhighlight lang=smalltalk>Collection extend
[
[
arithmeticMean
arithmeticMean
Line 3,352: Line 3,352:


((a arithmeticMean) >= (a geometricMean)) displayNl.
((a arithmeticMean) >= (a geometricMean)) displayNl.
((a geometricMean) >= (a harmonicMean)) displayNl.</lang>
((a geometricMean) >= (a harmonicMean)) displayNl.</syntaxhighlight>


{{out}}
{{out}}
Line 3,363: Line 3,363:
=={{header|SQL}}==
=={{header|SQL}}==
It may not be possible to calculate a geometric mean in a query, but the other two are easy enough.
It may not be possible to calculate a geometric mean in a query, but the other two are easy enough.
<lang sql>
<syntaxhighlight lang=sql>
--setup
--setup
create table averages (val integer);
create table averages (val integer);
Line 3,382: Line 3,382:
from
from
averages;
averages;
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,402: Line 3,402:
| Geometric 10 4.528729 2.680672 7.650836
| Geometric 10 4.528729 2.680672 7.650836
| Harmonic 10 3.414172 2.035664 10.57602
| Harmonic 10 3.414172 2.035664 10.57602
-----------------------------------------------------------------------------</lang>
-----------------------------------------------------------------------------</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>proc arithmeticMean list {
<syntaxhighlight lang=tcl>proc arithmeticMean list {
set sum 0.0
set sum 0.0
foreach value $list { set sum [expr {$sum + $value}] }
foreach value $list { set sum [expr {$sum + $value}] }
Line 3,427: Line 3,427:
puts "A10=$A10, G10=$G10, H10=$H10"
puts "A10=$A10, G10=$G10, H10=$H10"
if {$A10 >= $G10} { puts "A10 >= G10" }
if {$A10 >= $G10} { puts "A10 >= G10" }
if {$G10 >= $H10} { puts "G10 >= H10" }</lang>
if {$G10 >= $H10} { puts "G10 >= H10" }</syntaxhighlight>


{{out}}
{{out}}
Line 3,438: Line 3,438:
=={{header|Ursala}}==
=={{header|Ursala}}==


<lang Ursala>#import std
<syntaxhighlight lang=Ursala>#import std
#import flo
#import flo


Line 3,449: Line 3,449:
#cast %eLbX
#cast %eLbX


main = ^(~&,ordered not fleq) <a,g,h></lang>
main = ^(~&,ordered not fleq) <a,g,h></syntaxhighlight>
{{out}}
{{out}}
<pre>(
<pre>(
Line 3,458: Line 3,458:
Most valac setups will need "-X -lm" added to the compile command to include the C math library.
Most valac setups will need "-X -lm" added to the compile command to include the C math library.


<lang vala>
<syntaxhighlight lang=vala>
double arithmetic(int[] list){
double arithmetic(int[] list){
double mean;
double mean;
Line 3,511: Line 3,511:
stdout.printf("Harmonic mean: %s\n", harmonic_mean.to_string());
stdout.printf("Harmonic mean: %s\n", harmonic_mean.to_string());
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,522: Line 3,522:
=={{header|VBA}}==
=={{header|VBA}}==
Uses Excel VBA.
Uses Excel VBA.
<lang vb>Private Function arithmetic_mean(s() As Variant) As Double
<syntaxhighlight lang=vb>Private Function arithmetic_mean(s() As Variant) As Double
arithmetic_mean = WorksheetFunction.Average(s)
arithmetic_mean = WorksheetFunction.Average(s)
End Function
End Function
Line 3,537: Line 3,537:
Debug.Print "G ="; geometric_mean(s)
Debug.Print "G ="; geometric_mean(s)
Debug.Print "H ="; harmonic_mean(s)
Debug.Print "H ="; harmonic_mean(s)
End Sub</lang>{{out}}
End Sub</syntaxhighlight>{{out}}
<pre>A = 5,5
<pre>A = 5,5
G = 4,52872868811677
G = 4,52872868811677
Line 3,543: Line 3,543:


=={{header|VBScript}}==
=={{header|VBScript}}==
<syntaxhighlight lang=vb>
<lang vb>
Function arithmetic_mean(arr)
Function arithmetic_mean(arr)
sum = 0
sum = 0
Line 3,571: Line 3,571:
WScript.StdOut.WriteLine geometric_mean(Array(1,2,3,4,5,6,7,8,9,10))
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))
WScript.StdOut.WriteLine harmonic_mean(Array(1,2,3,4,5,6,7,8,9,10))
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 3,582: Line 3,582:
=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
{{trans|C#}}
{{trans|C#}}
<lang vbnet>Imports System.Runtime.CompilerServices
<syntaxhighlight lang=vbnet>Imports System.Runtime.CompilerServices


Module Module1
Module Module1
Line 3,609: Line 3,609:
End Sub
End Sub


End Module</lang>
End Module</syntaxhighlight>
{{out}}
{{out}}
<pre>Arithmetic mean 5.5
<pre>Arithmetic mean 5.5
Line 3,617: Line 3,617:
=={{header|Vlang}}==
=={{header|Vlang}}==
Updated for Vlang version 0.2.2
Updated for Vlang version 0.2.2
<lang go>import math
<syntaxhighlight lang=go>import math


fn main() {
fn main() {
Line 3,640: Line 3,640:
compare := if a >= g && g >= h { "Yes" } else { "Nope" }
compare := if a >= g && g >= h { "Yes" } else { "Nope" }
println('Is A >= G >= H? $compare')
println('Is A >= G >= H? $compare')
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Arithmetic Mean: 5.50
<pre>Arithmetic Mean: 5.50
Line 3,648: Line 3,648:


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>var rng = 1..10
<syntaxhighlight lang=ecmascript>var rng = 1..10
var count = rng.count
var count = rng.count
var A = rng.reduce { |acc, x| acc + x }/count
var A = rng.reduce { |acc, x| acc + x }/count
Line 3,658: Line 3,658:
System.print(" Geometric mean = %(G)")
System.print(" Geometric mean = %(G)")
System.print(" Harmonic mean = %(H)")
System.print(" Harmonic mean = %(H)")
System.print(" A >= G >= H = %(A >= G && G >= H)")</lang>
System.print(" A >= G >= H = %(A >= G && G >= H)")</syntaxhighlight>


{{out}}
{{out}}
Line 3,670: Line 3,670:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes;
<syntaxhighlight lang=XPL0>include c:\cxpl\codes;


func real Power(X, Y); \X raised to the Y power
func real Power(X, Y); \X raised to the Y power
Line 3,697: Line 3,697:
Text(0, "ALWAYS DECREASING ORDER
Text(0, "ALWAYS DECREASING ORDER
");
");
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 3,708: Line 3,708:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>ns:=T(1,2,3,4,5,6,7,8,9,10);
<syntaxhighlight lang=zkl>ns:=T(1,2,3,4,5,6,7,8,9,10);
ns.sum(0.0)/ns.len(); // Arithmetic mean
ns.sum(0.0)/ns.len(); // Arithmetic mean
ns.reduce('*,1.0).pow(1.0/ns.len()); // Geometric 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</lang>
ns.len().toFloat() / ns.reduce(fcn(p,n){ p + 1.0/n },0.0); // Harmonic mean</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>