Averages/Arithmetic mean: Difference between revisions
Langurmonkey (talk | contribs) |
|||
(115 intermediate revisions by 62 users not shown) | |||
Line 1: | Line 1: | ||
{{task|Probability and statistics}} |
{{task|Probability and statistics}} |
||
;Task |
|||
{{task heading}} |
|||
Write a program to find the [[wp:arithmetic mean|mean]] (arithmetic average) of a numeric vector. |
Write a program to find the [[wp:arithmetic mean|mean]] (arithmetic average) of a numeric vector. |
||
Line 14: | Line 14: | ||
=={{header|0815}}== |
=={{header|0815}}== |
||
< |
<syntaxhighlight lang="0815"> |
||
{x{+=<:2:x/%<:d:~$<:01:~><:02:~><:03:~><:04:~><:05:~><:06:~><:07:~><:08: |
{x{+=<:2:x/%<:d:~$<:01:~><:02:~><:03:~><:04:~><:05:~><:06:~><:07:~><:08: |
||
~><:09:~><:0a:~><:0b:~><:0c:~><:0d:~><:0e:~><:0f:~><:10:~><:11:~><:12:~> |
~><:09:~><:0a:~><:0b:~><:0c:~><:0d:~><:0e:~><:0f:~><:10:~><:11:~><:12:~> |
||
<:13:~><:14:~><:15:~><:16:~><:17:~><:18:~><:19:~><:ffffffffffffffff:~>{x |
<:13:~><:14:~><:15:~><:16:~><:17:~><:18:~><:19:~><:ffffffffffffffff:~>{x |
||
{+>}:8f:{&={+>{~>&=x<:ffffffffffffffff:/#:8f:{{=<:19:x/% |
{+>}:8f:{&={+>{~>&=x<:ffffffffffffffff:/#:8f:{{=<:19:x/% |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 25: | Line 25: | ||
D |
D |
||
</pre> |
</pre> |
||
=={{header|11l}}== |
|||
{{trans|Python}} |
|||
<syntaxhighlight lang="11l">F average(x) |
|||
R sum(x) / Float(x.len) |
|||
print(average([0, 0, 3, 1, 4, 1, 5, 9, 0, 0]))</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
2.3 |
|||
</pre> |
|||
=={{header|360 Assembly}}== |
=={{header|360 Assembly}}== |
||
Compact and functional. |
Compact and functional. |
||
< |
<syntaxhighlight lang="360asm">AVGP CSECT |
||
USING AVGP,12 |
USING AVGP,12 |
||
LR 12,15 |
LR 12,15 |
||
Line 53: | Line 65: | ||
Z DC CL80' ' |
Z DC CL80' ' |
||
U DS CL2 |
U DS CL2 |
||
END AVGP</ |
END AVGP</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 5.50</pre> |
<pre> 5.50</pre> |
||
Line 60: | Line 72: | ||
Called as a subroutine (i.e., JSR ArithmeticMean), this calculates the integer average of up to 255 8-bit unsigned integers. The address of the beginning of the list of integers is in the memory location ArrayPtr and the number of integers is in the memory location NumberInts. The arithmetic mean is returned in the memory location ArithMean. |
Called as a subroutine (i.e., JSR ArithmeticMean), this calculates the integer average of up to 255 8-bit unsigned integers. The address of the beginning of the list of integers is in the memory location ArrayPtr and the number of integers is in the memory location NumberInts. The arithmetic mean is returned in the memory location ArithMean. |
||
< |
<syntaxhighlight lang="6502asm">ArithmeticMean: PHA |
||
TYA |
TYA |
||
PHA ;push accumulator and Y register onto stack |
PHA ;push accumulator and Y register onto stack |
||
Line 99: | Line 111: | ||
TAY |
TAY |
||
PLA |
PLA |
||
RTS ;return from routine</ |
RTS ;return from routine</syntaxhighlight> |
||
=={{header|8th}}== |
=={{header|8th}}== |
||
< |
<syntaxhighlight lang="forth"> |
||
: avg \ a -- avg(a) |
: avg \ a -- avg(a) |
||
dup ' n:+ 0 a:reduce |
dup ' n:+ 0 a:reduce |
||
Line 112: | Line 124: | ||
[ 10 ] avg . cr |
[ 10 ] avg . cr |
||
bye |
bye |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output is:<br> |
Output is:<br> |
||
2.54395<br> |
2.54395<br> |
||
Line 119: | Line 131: | ||
=={{header|ACL2}}== |
=={{header|ACL2}}== |
||
< |
<syntaxhighlight lang="lisp">(defun mean-r (xs) |
||
(if (endp xs) |
(if (endp xs) |
||
(mv 0 0) |
(mv 0 0) |
||
Line 131: | Line 143: | ||
(mv-let (n d) |
(mv-let (n d) |
||
(mean-r xs) |
(mean-r xs) |
||
(/ n d))))</ |
(/ n d))))</syntaxhighlight> |
||
=={{header|Action!}}== |
|||
{{libheader|Action! Tool Kit}} |
|||
<syntaxhighlight lang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit |
|||
PROC Mean(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 Test(INT ARRAY a INT count) |
|||
INT i |
|||
REAL result |
|||
Mean(a,count,result) |
|||
Print("mean(") |
|||
FOR i=0 TO count-1 |
|||
DO |
|||
PrintI(a(i)) |
|||
IF i<count-1 THEN |
|||
Put(',) |
|||
FI |
|||
OD |
|||
Print(")=") |
|||
PrintRE(result) |
|||
RETURN |
|||
PROC Main() |
|||
INT ARRAY a1=[1 2 3 4 5 6] |
|||
INT ARRAY a2=[1 10 100 1000 10000] |
|||
INT ARRAY a3=[9] |
|||
Put(125) PutE() ;clear screen |
|||
Test(a1,6) |
|||
Test(a2,5) |
|||
Test(a3,1) |
|||
Test(a3,0) |
|||
RETURN</syntaxhighlight> |
|||
{{out}} |
|||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Arithmetic_mean.png Screenshot from Atari 8-bit computer] |
|||
<pre> |
|||
mean(1,2,3,4,5,6)=3.5 |
|||
mean(1,10,100,1000,10000)=2222.2 |
|||
mean(9)=9 |
|||
mean()=0 |
|||
</pre> |
|||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
< |
<syntaxhighlight lang="actionscript">function mean(vector:Vector.<Number>):Number |
||
{ |
{ |
||
var sum:Number = 0; |
var sum:Number = 0; |
||
Line 140: | Line 208: | ||
sum += vector[i]; |
sum += vector[i]; |
||
return vector.length == 0 ? 0 : sum / vector.length; |
return vector.length == 0 ? 0 : sum / vector.length; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
This example shows how to pass a zero length vector as well as a larger vector. |
This example shows how to pass a zero length vector as well as a larger vector. With Ada 2012 it is possible to check that pre conditions are satisfied (otherwise an exception is thrown). So we check that the length is not zero. |
||
< |
<syntaxhighlight lang="ada">with Ada.Float_Text_Io; use Ada.Float_Text_Io; |
||
with Ada.Text_IO; use Ada.Text_IO; |
with Ada.Text_IO; use Ada.Text_IO; |
||
procedure Mean_Main is |
procedure Mean_Main is |
||
type Vector is array(Positive range <>) of Float; |
type Vector is array (Positive range <>) of Float; |
||
function Mean(Item : Vector) return |
function Mean (Item : Vector) return float with pre => Item'length > 0; |
||
function Mean (Item : Vector) return Float is |
|||
Sum : Float := 0.0; |
Sum : Float := 0.0; |
||
Result : Float := 0.0; |
|||
begin |
begin |
||
for I in Item'range loop |
for I in Item'range loop |
||
Sum := Sum + Item(I); |
Sum := Sum + Item(I); |
||
end loop; |
end loop; |
||
return Sum / Float(Item'Length); |
|||
Result := Sum / Float(Item'Length); |
|||
end if; |
|||
return Result; |
|||
end Mean; |
end Mean; |
||
A : Vector := (3.0, 1.0, 4.0, 1.0, 5.0, 9.0); |
A : Vector := (3.0, 1.0, 4.0, 1.0, 5.0, 9.0); |
||
begin |
begin |
||
Put(Item => Mean(A), Fore => 1, Exp => 0); |
Put(Item => Mean (A), Fore => 1, Exp => 0); |
||
New_Line; |
New_Line; |
||
-- test for zero length vector |
-- test for zero length vector |
||
Put(Item => Mean(A(1..0)), Fore => 1, Exp => 0); |
Put(Item => Mean(A (1..0)), Fore => 1, Exp => 0); |
||
New_Line; |
New_Line; |
||
end Mean_Main;</ |
end Mean_Main;</syntaxhighlight> |
||
Output: |
Output: |
||
3.83333 |
|||
0.00000 |
|||
raised SYSTEM.ASSERTIONS.ASSERT_FAILURE : failed precondition from mean_main.adb:6 |
|||
=={{header|Aime}}== |
|||
<syntaxhighlight lang="aime">real |
|||
mean(list l) |
|||
{ |
|||
real sum, x; |
|||
sum = 0; |
|||
for (, x in l) { |
|||
sum += x; |
|||
} |
|||
sum / ~l; |
|||
} |
|||
integer |
|||
main(void) |
|||
{ |
|||
o_form("%f\n", mean(list(4.5, 7.25, 5r, 5.75))); |
|||
0; |
|||
}</syntaxhighlight> |
|||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
{{trans|C}} |
{{trans|C}} |
||
Line 178: | Line 267: | ||
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}} |
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}} |
||
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386 - note that some necessary LONG REAL operators are missing from ELLA's library.}} |
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386 - note that some necessary LONG REAL operators are missing from ELLA's library.}} |
||
< |
<syntaxhighlight lang="algol68">PROC mean = (REF[]REAL p)REAL: |
||
# Calculates the mean of qty REALs beginning at p. # |
# Calculates the mean of qty REALs beginning at p. # |
||
IF LWB p > UPB p THEN 0.0 |
IF LWB p > UPB p THEN 0.0 |
||
Line 190: | Line 279: | ||
[6]REAL test := (1.0, 2.0, 5.0, -5.0, 9.5, 3.14159); |
[6]REAL test := (1.0, 2.0, 5.0, -5.0, 9.5, 3.14159); |
||
print((mean(test),new line)) |
print((mean(test),new line)) |
||
)</ |
)</syntaxhighlight> |
||
=={{header|ALGOL W}}== |
=={{header|ALGOL W}}== |
||
< |
<syntaxhighlight lang="algolw">begin |
||
% procedure to find the mean of the elements of a vector. % |
% procedure to find the mean of the elements of a vector. % |
||
% As the procedure can't find the bounds of the array for itself, % |
% As the procedure can't find the bounds of the array for itself, % |
||
Line 214: | Line 303: | ||
r_format := "A"; r_w := 10; r_d := 2; % set fixed point output % |
r_format := "A"; r_w := 10; r_d := 2; % set fixed point output % |
||
write( mean( numbers, 1, 5 ) ); |
write( mean( numbers, 1, 5 ) ); |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|AmigaE}}== |
=={{header|AmigaE}}== |
||
Because of the way Amiga E handles floating point numbers, the passed list/vector must contain |
Because of the way Amiga E handles floating point numbers, the passed list/vector must contain |
||
all explicitly floating point values (e.g., you need to write "1.0", not "1") |
all explicitly floating point values (e.g., you need to write "1.0", not "1") |
||
< |
<syntaxhighlight lang="amigae">PROC mean(l:PTR TO LONG) |
||
DEF m, i, ll |
DEF m, i, ll |
||
ll := ListLen(l) |
ll := ListLen(l) |
||
Line 232: | Line 321: | ||
WriteF('mean \s\n', |
WriteF('mean \s\n', |
||
RealF(s,mean([1.0, 2.0, 3.0, 4.0, 5.0]), 2)) |
RealF(s,mean([1.0, 2.0, 3.0, 4.0, 5.0]), 2)) |
||
ENDPROC</ |
ENDPROC</syntaxhighlight> |
||
=={{header|AntLang}}== |
|||
AntLang has a built-in avg function. |
|||
<syntaxhighlight lang="antlang">avg[list]</syntaxhighlight> |
|||
=={{header|APL}}== |
|||
{{works with|APL2}} |
|||
<syntaxhighlight lang="apl"> |
|||
X←3 1 4 1 5 9 |
|||
(+/X)÷⍴X |
|||
3.833333333 |
|||
</syntaxhighlight> |
|||
{{works with|Dyalog APL}} |
|||
A proper function definition: |
|||
<syntaxhighlight lang="apl"> |
|||
Avg←{(+⌿⍵)÷≢⍵} |
|||
Avg 1 2 3 4 5 6 |
|||
3.5 |
|||
</syntaxhighlight> |
|||
Using [[tacit programming]]: |
|||
<syntaxhighlight lang="apl"> |
|||
Avg← +⌿÷≢ |
|||
Avg 1 2 3 4 5 6 |
|||
3.5 |
|||
</syntaxhighlight> |
|||
'''N.B.:''' the symbol for [https://aplwiki.com/wiki/Tally Tally (≢)] doesn't display correctly on Chrome-based browsers at the moment. |
|||
=={{header|AppleScript}}== |
|||
===Vanilla=== |
|||
With vanilla AppleScript, the process is the literal one of adding the numbers and dividing by the list length. It naturally returns results of class real, but it would be simple to return integer-representable results as integers if required. |
|||
<syntaxhighlight lang="applescript">on average(listOfNumbers) |
|||
set len to (count listOfNumbers) |
|||
if (len is 0) then return missing value |
|||
set sum to 0 |
|||
repeat with thisNumber in listOfNumbers |
|||
set sum to sum + thisNumber |
|||
end repeat |
|||
return sum / len |
|||
end average |
|||
average({2500, 2700, 2400, 2300, 2550, 2650, 2750, 2450, 2600, 2400})</syntaxhighlight> |
|||
{{output}} |
|||
<pre>2530.0</pre> |
|||
===ASObjC=== |
|||
The vanilla method above is the more efficient with lists of up to around 100 numbers. But for longer lists, using Foundation methods with AppleScriptObjectC can be useful |
|||
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later |
|||
use framework "Foundation" |
|||
on average(listOfNumbers) |
|||
if ((count listOfNumbers) is 0) then return missing value |
|||
set arrayOfNumbers to current application's class "NSArray"'s arrayWithArray:(listOfNumbers) |
|||
return (arrayOfNumbers's valueForKeyPath:("@avg.self")) as real |
|||
end average |
|||
average({2500, 2700, 2400, 2300, 2550, 2650, 2750, 2450, 2600, 2400})</syntaxhighlight> |
|||
{{output}} |
|||
<pre>2530.0</pre> |
|||
=={{header|Applesoft BASIC}}== |
=={{header|Applesoft BASIC}}== |
||
< |
<syntaxhighlight lang="applesoftbasic">REM COLLECTION IN DATA STATEMENTS, EMPTY DATA IS THE END OF THE COLLECTION |
||
0 READ V$ |
0 READ V$ |
||
1 IF LEN(V$) = 0 THEN END |
1 IF LEN(V$) = 0 THEN END |
||
Line 252: | Line 410: | ||
A(0) = 5 : A(1) = 1 : A(2) = 2 : A(3) = 2.718 : A(4) = 3 : A(5) = 3.142 |
A(0) = 5 : A(1) = 1 : A(2) = 2 : A(3) = 2.718 : A(4) = 3 : A(5) = 3.142 |
||
N = A(0) : IF N THEN S = 0 : FOR I = 1 TO N : S = S + A(I) : NEXT : ? S / N |
N = A(0) : IF N THEN S = 0 : FOR I = 1 TO N : S = S + A(I) : NEXT : ? S / N |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|AntLang}}== |
|||
=={{header|Arturo}}== |
|||
AntLang has a built-in avg function. |
|||
<lang AntLang>avg[list]</lang> |
|||
<syntaxhighlight lang="rebol">arr: [1 2 3 4 5 6 7] |
|||
print average arr</syntaxhighlight> |
|||
{{out}} |
|||
<pre>4.0</pre> |
|||
=={{header|Astro}}== |
|||
<syntaxhighlight lang="astro">mean([1, 2, 3]) |
|||
mean(1..10) |
|||
mean([]) |
|||
</syntaxhighlight> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">i = 10 |
||
Loop, % i { |
Loop, % i { |
||
Random, v, -3.141592, 3.141592 |
Random, v, -3.141592, 3.141592 |
||
Line 264: | Line 435: | ||
sum += v |
sum += v |
||
} |
} |
||
MsgBox, % i ? list "`nmean: " sum/i:0</ |
MsgBox, % i ? list "`nmean: " sum/i:0</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
< |
<syntaxhighlight lang="awk">cat mean.awk |
||
#!/usr/local/bin/gawk -f |
#!/usr/local/bin/gawk -f |
||
Line 291: | Line 462: | ||
print mean(nothing) |
print mean(nothing) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 299: | Line 470: | ||
zero-length input ! |
zero-length input ! |
||
</pre> |
</pre> |
||
=={{header|APL}}== |
|||
{{works with|APL2}} |
|||
<lang apl> X←3 1 4 1 5 9 |
|||
(+/X)÷⍴X |
|||
3.833333333</lang> |
|||
=={{header|Babel}}== |
=={{header|Babel}}== |
||
< |
<syntaxhighlight lang="babel">(3 24 18 427 483 49 14 4294 2 41) dup len <- sum ! -> / itod <<</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 317: | Line 482: | ||
Assume the numbers are in an array named "nums". |
Assume the numbers are in an array named "nums". |
||
< |
<syntaxhighlight lang="qbasic">mean = 0 |
||
sum = 0; |
sum = 0; |
||
FOR i = LBOUND(nums) TO UBOUND(nums) |
FOR i = LBOUND(nums) TO UBOUND(nums) |
||
Line 328: | Line 493: | ||
ELSE |
ELSE |
||
PRINT 0 |
PRINT 0 |
||
END IF</ |
END IF</syntaxhighlight> |
||
=={{header|BBC BASIC}}== |
==={{header|BBC BASIC}}=== |
||
{{works with|BBC BASIC for Windows}} |
{{works with|BBC BASIC for Windows}} |
||
To calculate the mean of an array: |
To calculate the mean of an array: |
||
<syntaxhighlight lang="bbc basic"> |
|||
<lang BBC BASIC> |
|||
REM specific functions for the array/vector types |
REM specific functions for the array/vector types |
||
Line 363: | Line 528: | ||
DEF FN_Mean_Arithmetic#(n#()) |
DEF FN_Mean_Arithmetic#(n#()) |
||
= SUM(n#()) / (DIM(n#(),1)+1) |
= SUM(n#()) / (DIM(n#(),1)+1) |
||
</syntaxhighlight> |
|||
</lang> |
|||
[[User:MichaelHutton|Michael Hutton]] 14:02, 29 May 2011 (UTC) |
[[User:MichaelHutton|Michael Hutton]] 14:02, 29 May 2011 (UTC) |
||
==={{header|IS-BASIC}}=== |
|||
<syntaxhighlight lang="is-basic">100 NUMERIC ARR(3 TO 8) |
|||
110 LET ARR(3)=3:LET ARR(4)=1:LET ARR(5)=4:LET ARR(6)=1:LET ARR(7)=5:LET ARR(8)=9 |
|||
120 PRINT AM(ARR) |
|||
130 DEF AM(REF A) |
|||
140 LET T=0 |
|||
150 FOR I=LBOUND(A) TO UBOUND(A) |
|||
160 LET T=T+A(I) |
|||
170 NEXT |
|||
180 LET AM=T/SIZE(A) |
|||
190 END DEF</syntaxhighlight> |
|||
=={{header|bc}}== |
=={{header|bc}}== |
||
Uses the current scale for calculating the mean. |
Uses the current scale for calculating the mean. |
||
< |
<syntaxhighlight lang="bc">define m(a[], n) { |
||
auto i, s |
auto i, s |
||
Line 375: | Line 552: | ||
} |
} |
||
return(s / n) |
return(s / n) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Befunge}}== |
=={{header|Befunge}}== |
||
The first input is the length of the vector. If a length of 0 is entered, the result is equal to <code>0/0</code>. |
The first input is the length of the vector. If a length of 0 is entered, the result is equal to <code>0/0</code>. |
||
< |
<syntaxhighlight lang="befunge">&:0\:!v!:-1< |
||
@./\$_\&+\^</ |
@./\$_\&+\^</syntaxhighlight> |
||
=={{header|blz}}== |
|||
<syntaxhighlight lang="blz"> |
|||
:mean(vec) |
|||
vec.fold_left(0, (x, y -> x + y)) / vec.length() |
|||
end</syntaxhighlight> |
|||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
Here are two solutions. The first uses a while loop, the second scans the input by backtracking. |
Here are two solutions. The first uses a while loop, the second scans the input by backtracking. |
||
< |
<syntaxhighlight lang="bracmat"> |
||
(mean1= |
(mean1= |
||
sum length n |
sum length n |
||
Line 409: | Line 592: | ||
| !sum*!length^-1 |
| !sum*!length^-1 |
||
); |
); |
||
</syntaxhighlight> |
|||
</lang> |
|||
To test with a list of all numbers 1 .. 999999: |
To test with a list of all numbers 1 .. 999999: |
||
< |
<syntaxhighlight lang="bracmat"> |
||
( :?test |
( :?test |
||
& 1000000:?Length |
& 1000000:?Length |
||
Line 417: | Line 600: | ||
& out$mean1$!test |
& out$mean1$!test |
||
& out$mean2$!test |
& out$mean2$!test |
||
)</ |
)</syntaxhighlight> |
||
=={{header|Brat}}== |
=={{header|Brat}}== |
||
< |
<syntaxhighlight lang="brat">mean = { list | |
||
true? list.empty?, 0, { list.reduce(0, :+) / list.length } |
true? list.empty?, 0, { list.reduce(0, :+) / list.length } |
||
} |
} |
||
p mean 1.to 10 #Prints 5.5</ |
p mean 1.to 10 #Prints 5.5</syntaxhighlight> |
||
=={{header|Burlesque}}== |
=={{header|Burlesque}}== |
||
< |
<syntaxhighlight lang="burlesque"> |
||
blsq ) {1 2 2.718 3 3.142}av |
blsq ) {1 2 2.718 3 3.142}av |
||
2.372 |
2.372 |
||
blsq ) {}av |
blsq ) {}av |
||
NaN |
NaN |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|BQN}}== |
|||
Defines a tacit Avg function which works on any simple numeric list. |
|||
<syntaxhighlight lang="bqn">Avg ← +´÷≠ |
|||
Avg 1‿2‿3‿4</syntaxhighlight> |
|||
<syntaxhighlight lang="text">2.5</syntaxhighlight> |
|||
[https://mlochbaum.github.io/BQN/try.html#code=QXZnIOKGkCArwrTDt+KJoAoKQXZnIDHigL8y4oC/M+KAvzQ= Try It!] |
|||
=={{header|C}}== |
=={{header|C}}== |
||
Compute mean of a <code>double</code> array of given length. If length is zero, does whatever <code>0.0/0</code> does (usually means returning <code>NaN</code>). |
Compute mean of a <code>double</code> array of given length. If length is zero, does whatever <code>0.0/0</code> does (usually means returning <code>NaN</code>). |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
double mean(double *v, int len) |
double mean(double *v, int len) |
||
Line 461: | Line 654: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight>{{out}}<pre> |
||
mean[1, 2, 2.718, 3, 3.142] = 2.372 |
mean[1, 2, 2.718, 3, 3.142] = 2.372 |
||
mean[1, 2, 2.718, 3] = 2.1795 |
mean[1, 2, 2.718, 3] = 2.1795 |
||
Line 470: | Line 663: | ||
</pre> |
</pre> |
||
=={{header|C sharp}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
using System.Linq; |
using System.Linq; |
||
Line 480: | Line 673: | ||
Console.WriteLine(new[] { 1, 2, 3 }.Average()); |
Console.WriteLine(new[] { 1, 2, 3 }.Average()); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Alternative version (not using the built-in function): |
Alternative version (not using the built-in function): |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
class Program |
class Program |
||
Line 511: | Line 704: | ||
return d / nums.Length; |
return d / nums.Length; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
{{libheader|STL}} |
{{libheader|STL}} |
||
< |
<syntaxhighlight lang="cpp">#include <vector> |
||
double mean(const std::vector<double>& numbers) |
double mean(const std::vector<double>& numbers) |
||
Line 526: | Line 719: | ||
sum += *i; |
sum += *i; |
||
return sum / numbers.size(); |
return sum / numbers.size(); |
||
}</ |
}</syntaxhighlight> |
||
Shorter (and more idiomatic) version: |
Shorter (and more idiomatic) version: |
||
< |
<syntaxhighlight lang="cpp">#include <vector> |
||
#include <algorithm> |
#include <algorithm> |
||
Line 538: | Line 731: | ||
return 0; |
return 0; |
||
return std::accumulate(numbers.begin(), numbers.end(), 0.0) / numbers.size(); |
return std::accumulate(numbers.begin(), numbers.end(), 0.0) / numbers.size(); |
||
}</ |
}</syntaxhighlight> |
||
Idiomatic version templated on any kind of iterator: |
Idiomatic version templated on any kind of iterator: |
||
< |
<syntaxhighlight lang="cpp">#include <iterator> |
||
#include <algorithm> |
#include <algorithm> |
||
Line 551: | Line 744: | ||
return 0; |
return 0; |
||
return std::accumulate(begin, end, 0.0) / std::distance(begin, end); |
return std::accumulate(begin, end, 0.0) / std::distance(begin, end); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Chef}}== |
=={{header|Chef}}== |
||
< |
<syntaxhighlight lang="chef">Mean. |
||
Chef has no way to detect EOF, so rather than interpreting |
Chef has no way to detect EOF, so rather than interpreting |
||
Line 585: | Line 778: | ||
Pour contents of mixing bowl into baking dish. |
Pour contents of mixing bowl into baking dish. |
||
Serves 1.</ |
Serves 1.</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
Returns a [http://clojure.org/data_structures ratio]: |
Returns a [http://clojure.org/data_structures ratio]: |
||
< |
<syntaxhighlight lang="lisp">(defn mean [sq] |
||
(if (empty? sq) |
(if (empty? sq) |
||
0 |
0 |
||
(/ (reduce + sq) (count sq))))</ |
(/ (reduce + sq) (count sq))))</syntaxhighlight> |
||
Returns a float: |
Returns a float: |
||
< |
<syntaxhighlight lang="lisp">(defn mean [sq] |
||
(if (empty? sq) |
(if (empty? sq) |
||
0 |
0 |
||
(float (/ (reduce + sq) (count sq)))))</ |
(float (/ (reduce + sq) (count sq)))))</syntaxhighlight> |
||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
Intrinsic function: |
Intrinsic function: |
||
< |
<syntaxhighlight lang="cobol">FUNCTION MEAN(some-table (ALL))</syntaxhighlight> |
||
Sample implementation: |
Sample implementation: |
||
< |
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION. |
||
PROGRAM-ID. find-mean. |
PROGRAM-ID. find-mean. |
||
Line 633: | Line 826: | ||
GOBACK |
GOBACK |
||
.</ |
.</syntaxhighlight> |
||
=={{header|Cobra}}== |
=={{header|Cobra}}== |
||
< |
<syntaxhighlight lang="cobra"> |
||
class Rosetta |
class Rosetta |
||
def mean(ns as List<of number>) as number |
def mean(ns as List<of number>) as number |
||
Line 651: | Line 844: | ||
print "mean of [[]] is [.mean(List<of number>())]" |
print "mean of [[]] is [.mean(List<of number>())]" |
||
print "mean of [[1,2,3,4]] is [.mean([1.0,2.0,3.0,4.0])]" |
print "mean of [[1,2,3,4]] is [.mean([1.0,2.0,3.0,4.0])]" |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
Line 660: | Line 853: | ||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
< |
<syntaxhighlight lang="coffeescript"> |
||
mean = (array) -> |
mean = (array) -> |
||
return 0 if array.length is 0 |
return 0 if array.length is 0 |
||
Line 668: | Line 861: | ||
alert mean [1] |
alert mean [1] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
'''With Reduce''' |
'''With Reduce''' |
||
< |
<syntaxhighlight lang="lisp">(defun mean (&rest sequence) |
||
( |
(when sequence |
||
(/ (reduce #'+ sequence) (length sequence))))</syntaxhighlight> |
|||
nil |
|||
(/ (reduce #'+ sequence) (length sequence))))</lang> |
|||
'''With Loop''' |
'''With Loop''' |
||
< |
<syntaxhighlight lang="lisp">(defun mean (list) |
||
( |
(when list |
||
(/ (loop for i in list sum i) |
(/ (loop for i in list sum i) |
||
(length list))))</ |
(length list))))</syntaxhighlight> |
||
=={{header|Craft Basic}}== |
|||
<syntaxhighlight lang="basic">dim a[3, 1, 4, 1, 5, 9] |
|||
arraysize s, a |
|||
for i = 0 to s - 1 |
|||
let t = t + a[i] |
|||
next i |
|||
print t / s</syntaxhighlight> |
|||
{{out| Output}}<pre>3.83</pre> |
|||
=={{header|Crystal}}== |
|||
<syntaxhighlight lang="ruby"># Crystal will return NaN if an empty array is passed |
|||
def mean(arr) : Float64 |
|||
arr.sum / arr.size.to_f |
|||
end</syntaxhighlight> |
|||
=={{header|D}}== |
=={{header|D}}== |
||
===Imperative Version=== |
===Imperative Version=== |
||
< |
<syntaxhighlight lang="d">real mean(Range)(Range r) pure nothrow @nogc { |
||
real sum = 0.0; |
real sum = 0.0; |
||
int count; |
int count; |
||
Line 708: | Line 920: | ||
data = [3, 1, 4, 1, 5, 9]; |
data = [3, 1, 4, 1, 5, 9]; |
||
writeln("Mean: ", data.mean); |
writeln("Mean: ", data.mean); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>mean: 0 |
<pre>mean: 0 |
||
mean: 3.83333</pre> |
mean: 3.83333</pre> |
||
===More Functional Version=== |
===More Functional Version=== |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.range; |
||
real mean(Range)(Range r) pure nothrow @nogc { |
real mean(Range)(Range r) pure nothrow @nogc { |
||
Line 722: | Line 934: | ||
writeln("Mean: ", (int[]).init.mean); |
writeln("Mean: ", (int[]).init.mean); |
||
writeln("Mean: ", [3, 1, 4, 1, 5, 9].mean); |
writeln("Mean: ", [3, 1, 4, 1, 5, 9].mean); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Mean: 0 |
<pre>Mean: 0 |
||
Line 729: | Line 941: | ||
===More Precise Version=== |
===More Precise Version=== |
||
A (naive?) version that tries to minimize precision loss (but already the sum algorithm applied to a random access range of floating point values uses a more precise summing strategy): |
A (naive?) version that tries to minimize precision loss (but already the sum algorithm applied to a random access range of floating point values uses a more precise summing strategy): |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.conv, std.algorithm, std.math, std.traits; |
||
CommonType!(T, real) mean(T)(T[] n ...) if (isNumeric!T) { |
CommonType!(T, real) mean(T)(T[] n ...) if (isNumeric!T) { |
||
Line 742: | Line 954: | ||
writefln("%8.5f", mean( 0, 3, 1, 4, 1, 5, 9, 0)); |
writefln("%8.5f", mean( 0, 3, 1, 4, 1, 5, 9, 0)); |
||
writefln("%8.5f", mean([-1e20, 3, 1, 4, 1, 5, 9, 1e20])); |
writefln("%8.5f", mean([-1e20, 3, 1, 4, 1, 5, 9, 1e20])); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 0.00000 |
<pre> 0.00000 |
||
Line 749: | Line 961: | ||
=={{header|Dart}}== |
=={{header|Dart}}== |
||
< |
<syntaxhighlight lang="d">num mean(List<num> l) => l.reduce((num p, num n) => p + n) / l.length; |
||
void main(){ |
void main(){ |
||
print(mean([1,2,3,4,5,6,7])); |
print(mean([1,2,3,4,5,6,7])); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>4.0</pre> |
<pre>4.0</pre> |
||
Line 760: | Line 972: | ||
This is not a translation of the bc solution. Array handling would add some complexity. This one-liner is similar to the K solution. |
This is not a translation of the bc solution. Array handling would add some complexity. This one-liner is similar to the K solution. |
||
< |
<syntaxhighlight lang="dc">1 2 3 5 7 zsn1k[+z1<+]ds+xln/p |
||
3.6</ |
3.6</syntaxhighlight> |
||
An expanded example, identifying an empty sample set, could be created as a file,e.g., amean.cd: |
An expanded example, identifying an empty sample set, could be created as a file, e.g., amean.cd: |
||
< |
<syntaxhighlight lang="dc">[[Nada Mean: ]Ppq]sq |
||
zd0=qsn [stack length = n]sz |
zd0=qsn [stack length = n]sz |
||
1k [precision can be altered]sz |
1k [precision can be altered]sz |
||
[+z1<+]ds+x[Sum: ]Pp |
|||
ln/[Mean: ]Pp [Sample size: ]Plnp</lang> |
|||
ln/[Mean: ]Pp |
|||
[Sample size: ]Plnp</syntaxhighlight> |
|||
By saving the sample set "1 2 3 5 7" in a file (sample.dc), the routine, listing summary information, could be called in a command line: |
By saving the sample set "1 2 3 5 7" in a file (sample.dc), the routine, listing summary information, could be called in a command line: |
||
< |
<syntaxhighlight lang="dc">$ dc sample.dc amean.cd |
||
Sum: 18 |
Sum: 18 |
||
Mean: 3.6 |
Mean: 3.6 |
||
Sample size: 5 |
Sample size: 5 |
||
$</ |
$</syntaxhighlight> |
||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
< |
<syntaxhighlight lang="delphi">program AveragesArithmeticMean; |
||
{$APPTYPE CONSOLE} |
{$APPTYPE CONSOLE} |
||
Line 800: | Line 1,014: | ||
Writeln(Mean(TDoubleDynArray.Create())); |
Writeln(Mean(TDoubleDynArray.Create())); |
||
Writeln(Mean(TDoubleDynArray.Create(1,2,3,4,5))); |
Writeln(Mean(TDoubleDynArray.Create(1,2,3,4,5))); |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|Dyalect}}== |
|||
<syntaxhighlight lang="dyalect">func avg(args...) { |
|||
var acc = .0 |
|||
var len = 0 |
|||
for x in args { |
|||
len += 1 |
|||
acc += x |
|||
} |
|||
acc / len |
|||
} |
|||
avg(1, 2, 3, 4, 5, 6)</syntaxhighlight> |
|||
=={{header|E}}== |
=={{header|E}}== |
||
Line 806: | Line 1,034: | ||
Slightly generalized to support any object that allows iteration. |
Slightly generalized to support any object that allows iteration. |
||
< |
<syntaxhighlight lang="e">def meanOrZero(numbers) { |
||
var count := 0 |
var count := 0 |
||
var sum := 0 |
var sum := 0 |
||
Line 814: | Line 1,042: | ||
} |
} |
||
return sum / 1.max(count) |
return sum / 1.max(count) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|EasyLang}}== |
|||
<syntaxhighlight lang="text"> |
|||
proc mean . f[] r . |
|||
for i = 1 to len f[] |
|||
s += f[i] |
|||
. |
|||
r = s / len f[] |
|||
. |
|||
f[] = [ 1 2 3 4 5 6 7 8 ] |
|||
mean f[] r |
|||
print r |
|||
</syntaxhighlight> |
|||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
'''(mean values)''' is included in math.lib. values may be a list, vector, sequence, or any kind of procrastinator. |
'''(mean values)''' is included in math.lib. values may be a list, vector, sequence, or any kind of procrastinator. |
||
< |
<syntaxhighlight lang="scheme"> |
||
(lib 'math) |
(lib 'math) |
||
(mean '(1 2 3 4)) ;; mean of a list |
(mean '(1 2 3 4)) ;; mean of a list |
||
Line 840: | Line 1,081: | ||
😁 warning: mean : zero-divide : empty-sequence |
😁 warning: mean : zero-divide : empty-sequence |
||
→ 0 |
→ 0 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ECL}}== |
=={{header|ECL}}== |
||
< |
<syntaxhighlight lang="ecl"> |
||
AveVal(SET OF INTEGER s) := AVE(s); |
AveVal(SET OF INTEGER s) := AVE(s); |
||
Line 850: | Line 1,091: | ||
SetVals := [14,9,16,20,91]; |
SetVals := [14,9,16,20,91]; |
||
AveVal(SetVals) //returns 30.0 ; |
AveVal(SetVals) //returns 30.0 ; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|EDSAC order code}}== |
|||
Extends the RC task by finding the arithmetic mean for each of several data sets. Each data set is preceded by the number of data. A count of 0 is not an error but signals that there are no more data sets. |
|||
The program needs to avoid the possibility of arithmetic overflow, as pointed out in the F# solution. The moving average used there is not well-suited to EDSAC, on which division had to be done by calling a subroutine. After reading the number of data N, and leaving the trivial case N = 1 for separate treatment, the program first calculates 1/N, then multiplies each value by 1/N before adding it into the result. |
|||
<syntaxhighlight lang="edsac"> |
|||
[Averages/Arithmetic mean - Rosetta Code] |
|||
[EDSAC program (Initial Orders 2) to find and print the average of |
|||
a sequence of 35-bit fractional values. |
|||
Values are read from tape, preceded by an integer count.] |
|||
[Library subroutine M3, runs at load time and is then overwritten. |
|||
Prints header; here, last character sets teleprinter to figures.] |
|||
PF GK IF AF RD LF UF OF E@ A6F G@ E8F EZ PF |
|||
*!!!!!COUNT!!!!!!AVERAGE@&#.. [PZ] |
|||
[Main routine: must be at even address] |
|||
T214K GK |
|||
[0] PF PF [average value] |
|||
[2] PF PF [reciprocal of data count] |
|||
[4] PF [data count] |
|||
[5] PD [17-bit constant 1; also serves as '0' for printing] |
|||
[6] @F [carriage return] |
|||
[7] &F [line feed] |
|||
[8] !F [space] |
|||
[9] MF [dot (in figures mode)] |
|||
[10] K4096F [teleprinter null] |
|||
[Entry and outer loop] |
|||
[11] A11@ |
|||
G56F [call library subroutine R4, sets 0D := data count N] |
|||
SD E64@ [exit if N = 0] |
|||
T4F [clear acc] |
|||
AF T4@ [load and save N (assumed < 2^16)] |
|||
[18] A18@ G156F [print N (clears acc)] |
|||
TD [clear whole of 0D, including sandwich bit] |
|||
T4D [same for 4D] |
|||
A4@ S2F [acc := N - 2] |
|||
G66@ [jump to special action if N = 1] |
|||
A2F [restore N after test] |
|||
T5F [store N in 4D high word] |
|||
A5@ T1F [store 1 in 0D high word] |
|||
[29] A29@ G120F [call library subroutine D6, sets 0D := 0D/4D] |
|||
AD T2#@ [load and save 1/N] |
|||
T#@ [clear average] |
|||
S4@ [load -N] |
|||
[Inner loop] |
|||
[35] T4@ [update negative loop counter] |
|||
[36] A36@ G78F [read next datum to 0D (clears acc)] |
|||
H2#@ [mult reg := 1/N] |
|||
VD [acc := datum/N] |
|||
A#@ T#@ [add into average] |
|||
A4@ A5@ [increment negative loop counter] |
|||
G35@ [loop until counter = 0] |
|||
[45] O8@ O8@ [print 2 spaces] |
|||
[Print the average value. |
|||
NB: Library subroutine P1 requires non-negative input and prints only the |
|||
digits after the decimal point. Formatting has to be done by the caller.] |
|||
[47] A#@ [load average (order also serves as minus sign)] |
|||
G52@ [jump if average < 0] |
|||
TD [pass average to subroutine P1] |
|||
O65@ [print plus sign (or could be space)] |
|||
E56@ [join common code] |
|||
[52] TD [average < 0; clear acc] |
|||
S#@ TD [pass abs(average) to subroutine P1] |
|||
O47@ [print minus sign] |
|||
[56] O5@ O9@ [common code: print '0.'] |
|||
[58] A58@ G192F [call P1 to print abs(average)] |
|||
P8F [8 decimal places] |
|||
O6@ O7@ [print CR, LF] |
|||
E11@ [loop back always (because acc = 0)] |
|||
[Jump to here if data count = 0, means end of data] |
|||
[64] O10@ [print null to flush teleprinter buffer] |
|||
[65] ZF [halt the machine (order also serves as plus sign)] |
|||
[Jump to here if data count = 1] |
|||
[66] TF [clear acc] |
|||
[67] A67@ G78F [read datum to 0D] |
|||
AD T#@ [average := datum] |
|||
E45@ [jump to print the average] |
|||
[The following puts the entry address into location 50, |
|||
so that it can be accessed via the X parameter (see end of program). |
|||
This is done in case the data is input from a separate tape.] |
|||
T50K P11@ T11Z |
|||
[Library subroutine R4. |
|||
Input of one signed integer, returned in 0D.] |
|||
T56K |
|||
GKA3FT21@T4DH6@E11@P5DJFT6FVDL4FA4DTDI4FA4FS5@G7@S5@G20@SDTDT6FEF |
|||
[Library subroutine R3. |
|||
Input of one long signed decimal fraction, returned in 0D.] |
|||
T78K |
|||
GKT45KP26@TZA3FTHTDT4DA6HT9@H1HS4HT6FIFAFS4HE7HT7FV4DL8FADT4DA6FA5HG8@ |
|||
H2#HN4DLDYFTDT28#ZPFT27ZTFP610D@524DP5DPDIFS4HG37@S4DT4DT7FA1HT9@E18@ |
|||
[Library subroutine D6 - Division, accurate, fast. |
|||
36 locations, workspace 6D and 8D. |
|||
0D := 0D/4D, where 4D <> 0, -1.] |
|||
T120K |
|||
GKA3FT34@S4DE13@T4DSDTDE2@T4DADLDTDA4DLDE8@RDU4DLDA35@ |
|||
T6DE25@U8DN8DA6DT6DH6DS6DN4DA4DYFG21@SDVDTDEFW1526D |
|||
[Library subroutine P7: print strictly positive integer in 0D.] |
|||
T156K |
|||
GKA3FT26@H28#@NDYFLDT4DS27@TFH8@S8@T1FV4DAFG31@SFLDUFOFFFSF |
|||
L4FT4DA1FA27@G11@T28#ZPFT27ZP1024FP610D@524D!FO30@SFL8FE22@ |
|||
[Library subroutine P1: print non-negative fraction in 0D, without '0.'] |
|||
T192K |
|||
GKA18@U17@S20@T5@H19@PFT5@VDUFOFFFSFL4FTDA5@A2FG6@EFU3FJFM1F |
|||
[========================================================================== |
|||
On the original EDSAC, the following (without the whitespace and comments) |
|||
might have been input on a separate tape.] |
|||
E25K TX GK |
|||
EZ [define entry point] |
|||
PF [acc = 0 on entry] |
|||
[Counts and data values to be read by library subroutines R3 and R4 respectively. |
|||
Note (1) Sign comes *after* value (2) In the data, leading '0.' is omitted.] |
|||
7+ 1-2-3-4-5+2-3- |
|||
1+ 987654321+ |
|||
9+ 01+04+09+16+25+36+49+64+81+ |
|||
9+ 01-04+09-16+25-36+49-64+81- |
|||
[Daily minimum temperature (unit = 10 deg. C), Cambridge, UK, January 2000] |
|||
31+ 34+14+49+00+04+48+05+48+23-35-07-75+19+03+ |
|||
26+27+17-06-52+22-17+18+15+03-33-11-04-01-44+89+95+ |
|||
0+ |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
COUNT AVERAGE |
|||
7 -0.14285714 |
|||
1 +0.98765432 |
|||
9 +0.31666666 |
|||
9 -0.05000000 |
|||
31 +0.16774193 |
|||
</pre> |
|||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA 6.x: |
|||
<lang elena>#define system. |
|||
<syntaxhighlight lang="elena">import extensions; |
|||
extension op |
|||
{ |
{ |
||
average() |
|||
{ |
|||
real sum := 0; |
|||
int count := 0; |
|||
var enumerator := self.enumerator(); |
|||
while (enumerator.next()) |
|||
{ |
|||
sum += *enumerator; |
|||
count += 1; |
|||
}; |
|||
^ |
^ sum / count |
||
} |
|||
} |
} |
||
public program() |
|||
{ |
|||
[ |
|||
var array := new int[]{1, 2, 3, 4, 5, 6, 7, 8}; |
|||
console.printLine( |
|||
console writeLine:"Arithmetic mean of {":anArray:"} is ":(anArray average). |
|||
"Arithmetic mean of {",array.asEnumerable(),"} is ", |
|||
]. </lang> |
|||
array.average()).readChar() |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Arithmetic mean of {1,2,3,4,5,6,7,8} is 4.5 |
|||
</pre> |
|||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
< |
<syntaxhighlight lang="elixir">defmodule Average do |
||
def mean(list), do: Enum.sum(list) / length(list) |
def mean(list), do: Enum.sum(list) / length(list) |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
<lang |
<syntaxhighlight lang="lisp">(defun mean (lst) |
||
(/ (float (apply '+ lst)) (length lst))) |
|||
(mean '(1 2 3 4))</syntaxhighlight> |
|||
{{libheader|Calc}} |
|||
Calculate mean by Emacs Lisp and built-in Emacs Calc |
|||
< |
<syntaxhighlight lang="lisp">(let ((x '(1 2 3 4))) |
||
(calc-eval "vmean($1)" nil (append '(vec) x)))</syntaxhighlight> |
|||
=={{header|EMal}}== |
|||
<syntaxhighlight lang="emal"> |
|||
fun mean = real by some real values |
|||
real sum |
|||
int count |
|||
for each real value in values |
|||
sum += value |
|||
++count |
|||
end |
|||
return when(count == 0, 0.0, sum / count) |
|||
end |
|||
writeLine(mean()) |
|||
writeLine(mean(3,1,4,1,5,9)) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
0.0 |
|||
3.8333333333333333333333333333 |
|||
</pre> |
|||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<syntaxhighlight lang="erlang">mean([]) -> 0; |
||
mean(L) -> lists:sum(L)/erlang:length(L).</ |
mean(L) -> lists:sum(L)/erlang:length(L).</syntaxhighlight> |
||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
< |
<syntaxhighlight lang="euphoria">function mean(sequence s) |
||
atom sum |
atom sum |
||
if length(s) = 0 then |
if length(s) = 0 then |
||
Line 915: | Line 1,323: | ||
sequence test |
sequence test |
||
test = {1.0, 2.0, 5.0, -5.0, 9.5, 3.14159} |
test = {1.0, 2.0, 5.0, -5.0, 9.5, 3.14159} |
||
? mean(test)</ |
? mean(test)</syntaxhighlight> |
||
=={{header|Excel}}== |
=={{header|Excel}}== |
||
Assuming the values are entered in the A column, type into any cell which will not be part of the list: |
Assuming the values are entered in the A column, type into any cell which will not be part of the list: |
||
< |
<syntaxhighlight lang="excel">=AVERAGE(A1:A10)</syntaxhighlight> |
||
Assuming 10 values will be entered, alternatively, you can just type: |
Assuming 10 values will be entered, alternatively, you can just type: |
||
< |
<syntaxhighlight lang="excel">=AVERAGE(</syntaxhighlight> |
||
and then select the start and end cells, not necessarily in the same row or column. |
and then select the start and end cells, not necessarily in the same row or column. |
||
Line 942: | Line 1,350: | ||
10 |
10 |
||
</pre> |
</pre> |
||
=={{header|F_Sharp|F#}}== |
|||
The following computes the running mean using a tail-recursive approach. If we just sum all the values then divide by the number of values then we will suffer from overflow problems for large lists. See [[wp:Moving_average|wikipedia]] about the moving average computation. |
|||
<syntaxhighlight lang="fsharp">let avg (a:float) (v:float) n = |
|||
a + (1. / ((float n) + 1.)) * (v - a) |
|||
let mean_series list = |
|||
let a, _ = List.fold_left (fun (a, n) h -> avg a (float h) n, n + 1) (0., 0) list in |
|||
a</syntaxhighlight> |
|||
Checking this: |
|||
<syntaxhighlight lang="fsharp"> > mean_series [1; 8; 2; 8; 1; 7; 1; 8; 2; 7; 3; 6; 1; 8; 100] ;; |
|||
val it : float = 10.86666667 |
|||
> mean_series [] ;; |
|||
val it : float = 0.0</syntaxhighlight> |
|||
We can also make do with the built-in ''List.average'' function: |
|||
<syntaxhighlight lang="fsharp">List.average [4;1;7;5;8;4;5;2;1;5;2;5]</syntaxhighlight> |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang="factor">USING: math math.statistics ; |
||
: arithmetic-mean ( seq -- n ) |
: arithmetic-mean ( seq -- n ) |
||
[ 0 ] [ mean ] if-empty ;</ |
[ 0 ] [ mean ] if-empty ;</syntaxhighlight> |
||
Tests: |
Tests: |
||
< |
<syntaxhighlight lang="factor">( scratchpad ) { 2 3 5 } arithmetic-mean >float |
||
3.333333333333333</ |
3.333333333333333</syntaxhighlight> |
||
=={{header|Fantom}}== |
=={{header|Fantom}}== |
||
< |
<syntaxhighlight lang="fantom"> |
||
class Main |
class Main |
||
{ |
{ |
||
Line 975: | Line 1,401: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Fish}}== |
=={{header|Fish}}== |
||
< |
<syntaxhighlight lang="fish">!vl0=?vl1=?vl&! |
||
v< +<>0n; >n; |
v< +<>0n; >n; |
||
>l1)?^&,n;</ |
>l1)?^&,n;</syntaxhighlight> |
||
Must be called with the values pre-populated on the stack, which can be done in the <tt>fish.py</tt> interpreter with the <tt>-v</tt> switch: |
Must be called with the values pre-populated on the stack, which can be done in the <tt>fish.py</tt> interpreter with the <tt>-v</tt> switch: |
||
<pre>fish.py mean.fish -v 10 100 47 207.4</pre> |
<pre>fish.py mean.fish -v 10 100 47 207.4</pre> |
||
Line 987: | Line 1,413: | ||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang="forth">: fmean ( addr n -- f ) |
||
0e |
0e |
||
dup 0= if 2drop exit then |
dup 0= if 2drop exit then |
||
Line 996: | Line 1,422: | ||
create test 3e f, 1e f, 4e f, 1e f, 5e f, 9e f, |
create test 3e f, 1e f, 4e f, 1e f, 5e f, 9e f, |
||
test 6 fmean f. \ 3.83333333333333</ |
test 6 fmean f. \ 3.83333333333333</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
In ISO Fortran 90 or later, use the SUM intrinsic, the SIZE intrinsic and the MAX intrinsic (to avoid divide by zero): |
In ISO Fortran 90 or later, use the SUM intrinsic, the SIZE intrinsic and the MAX intrinsic (to avoid divide by zero): |
||
< |
<syntaxhighlight lang="fortran">real, target, dimension(100) :: a = (/ (i, i=1, 100) /) |
||
real, dimension(5,20) :: b = reshape( a, (/ 5,20 /) ) |
real, dimension(5,20) :: b = reshape( a, (/ 5,20 /) ) |
||
real, pointer, dimension(:) :: p => a(2:1) ! pointer to zero-length array |
real, pointer, dimension(:) :: p => a(2:1) ! pointer to zero-length array |
||
Line 1,019: | Line 1,445: | ||
! dividing by the length of the row, which is the number of columns (SIZE of dimension 2) |
! dividing by the length of the row, which is the number of columns (SIZE of dimension 2) |
||
colmeans = sum(b,2)/max(size(b,1),1) ! SUM elements in each column (dimension 2) |
colmeans = sum(b,2)/max(size(b,1),1) ! SUM elements in each column (dimension 2) |
||
! dividing by the length of the column, which is the number of rows (SIZE of dimension 1)</ |
! dividing by the length of the column, which is the number of rows (SIZE of dimension 1)</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic"> |
||
' FB 1.05.0 Win64 |
' FB 1.05.0 Win64 |
||
Line 1,065: | Line 1,491: | ||
Print "Press any key to quit the program" |
Print "Press any key to quit the program" |
||
Sleep |
Sleep |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 1,087: | Line 1,513: | ||
=={{header|Frink}}== |
=={{header|Frink}}== |
||
The following works on arrays or sets. If the collection is empty, this returns the special value <CODE>undef</CODE>. |
The following works on arrays or sets. If the collection is empty, this returns the special value <CODE>undef</CODE>. |
||
< |
<syntaxhighlight lang="frink"> |
||
mean[x] := length[x] > 0 ? sum[x] / length[x] : undef |
mean[x] := length[x] > 0 ? sum[x] / length[x] : undef |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|F_Sharp|F#}}== |
|||
The following computes the running mean using a tail-recursive approach. If we just sum all the values then divide by the number of values then we will suffer from overflow problems for large lists. See [[wp:Moving_average|wikipedia]] about the moving average computation. |
|||
<lang fsharp>let avg (a:float) (v:float) n = |
|||
a + (1. / ((float n) + 1.)) * (v - a) |
|||
let mean_series list = |
|||
let a, _ = List.fold_left (fun (a, n) h -> avg a (float h) n, n + 1) (0., 0) list in |
|||
a</lang> |
|||
=={{header|FutureBasic}}== |
|||
Checking this: |
|||
<syntaxhighlight lang="futurebasic"> |
|||
<lang fsharp> > mean_series [1; 8; 2; 8; 1; 7; 1; 8; 2; 7; 3; 6; 1; 8; 100] ;; |
|||
local fn MeanAverageOfNumberArray( numberArr as CFArrayRef ) as CFStringRef |
|||
val it : float = 10.86666667 |
|||
CFStringRef result = NULL |
|||
> mean_series [] ;; |
|||
if len(numberArr) == 0 then result = @"Mean undefined for empty array." : exit fn |
|||
val it : float = 0.0</lang> |
|||
result = fn StringWithFormat( @"Mean average of %d numbers: %@", len(numberArr), fn ObjectValueForKeyPath( numberArr, @"@avg.self" ) ) |
|||
end fn = result |
|||
CFArrayRef numberArray |
|||
We can also make do with the built-in ''List.average'' function: |
|||
numberArray = @[@1, @2, @3, @4, @5, @6, @7, @8, @9, @10] |
|||
<lang fsharp>List.average [4;1;7;5;8;4;5;2;1;5;2;5]</lang> |
|||
print fn MeanAverageOfNumberArray( numberArray ) |
|||
numberArray = @[@3, @1, @4, @1, @5, @9] |
|||
print fn MeanAverageOfNumberArray( numberArray ) |
|||
HandleEvents |
|||
</syntaxhighlight> |
|||
{{output}} |
|||
<pre> |
|||
Mean average of 10 numbers: 5.5 |
|||
Man average of 6 numbers: 3.83333333333333333333333333333333333333 |
|||
</pre> |
|||
</pre> |
|||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang="gap">Mean := function(v) |
||
local n; |
local n; |
||
n := Length(v); |
n := Length(v); |
||
Line 1,121: | Line 1,556: | ||
Mean([3, 1, 4, 1, 5, 9]); |
Mean([3, 1, 4, 1, 5, 9]); |
||
# 23/6</ |
# 23/6</syntaxhighlight> |
||
=={{header|GEORGE}}== |
=={{header|GEORGE}}== |
||
< |
<syntaxhighlight lang="george">R (n) P ; |
||
0 |
0 |
||
1, n rep (i) |
1, n rep (i) |
||
Line 1,130: | Line 1,565: | ||
] |
] |
||
n div |
n div |
||
P</ |
P</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 1,150: | Line 1,585: | ||
This works for arrays of integers. |
This works for arrays of integers. |
||
<lang> |
<syntaxhighlight lang="text"> |
||
DIM a%(10) |
DIM a%(10) |
||
FOR i%=0 TO 10 |
FOR i%=0 TO 10 |
||
Line 1,174: | Line 1,609: | ||
RETURN sum/size% |
RETURN sum/size% |
||
ENDFUNC |
ENDFUNC |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Go}}== |
=={{header|Go}}== |
||
A little more elaborate that the task requires. The function "mean" fulfills the task of "a program to find the mean." As a Go idiom, it returns an ok value of true if result m is valid. An ok value of false means the input "vector" (a Go slice) was empty. The fancy accuracy preserving algorithm is a little more than was called more. The program main is a test program demonstrating the ok idiom and several data cases. |
A little more elaborate that the task requires. The function "mean" fulfills the task of "a program to find the mean." As a Go idiom, it returns an ok value of true if result m is valid. An ok value of false means the input "vector" (a Go slice) was empty. The fancy accuracy preserving algorithm is a little more than was called more. The program main is a test program demonstrating the ok idiom and several data cases. |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 1,243: | Line 1,678: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,269: | Line 1,704: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
< |
<syntaxhighlight lang="groovy">def avg = { list -> list == [] ? 0 : list.sum() / list.size() }</syntaxhighlight> |
||
Test Program: |
Test Program: |
||
< |
<syntaxhighlight lang="groovy">println avg(0..9) |
||
println avg([2,2,2,4,2]) |
println avg([2,2,2,4,2]) |
||
println avg ([])</ |
println avg ([])</syntaxhighlight> |
||
Output: |
Output: |
||
Line 1,283: | Line 1,718: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
This function works if the element type is an instance of Fractional: |
This function works if the element type is an instance of Fractional: |
||
< |
<syntaxhighlight lang="haskell">mean :: (Fractional a) => [a] -> a |
||
mean [] = 0 |
mean [] = 0 |
||
mean xs = sum xs / Data.List.genericLength xs</ |
mean xs = sum xs / Data.List.genericLength xs</syntaxhighlight> |
||
But some types, e.g. integers, are not Fractional; the following function works for all Real types: |
But some types, e.g. integers, are not Fractional; the following function works for all Real types: |
||
< |
<syntaxhighlight lang="haskell">meanReals :: (Real a, Fractional b) => [a] -> b |
||
meanReals = mean . map realToFrac</ |
meanReals = mean . map realToFrac</syntaxhighlight> |
||
If you want to avoid keeping the list in memory and traversing it twice: |
If you want to avoid keeping the list in memory and traversing it twice: |
||
< |
<syntaxhighlight lang="haskell">{-# LANGUAGE BangPatterns #-} |
||
import Data.List (foldl') |
|||
import Data.List (foldl') --' |
|||
mean :: (Real n, Fractional m) => [n] -> m |
|||
mean xs = let (s,l) = foldl' f (0, 0) xs in realToFrac s / l |
|||
mean |
|||
where f (!s,!l) x = (s+x,l+1)</lang> |
|||
:: (Real n, Fractional m) |
|||
=> [n] -> m |
|||
mean xs = |
|||
let (s, l) = |
|||
foldl' --' |
|||
f |
|||
(0, 0) |
|||
xs |
|||
in realToFrac s / l |
|||
where |
|||
f (!s, !l) x = (s + x, l + 1) |
|||
main :: IO () |
|||
main = print $ mean [1 .. 100]</syntaxhighlight> |
|||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
< |
<syntaxhighlight lang="hicest">REAL :: vec(100) ! no zero-length arrays in HicEst |
||
vec = $ - 1/2 ! 0.5 ... 99.5 |
vec = $ - 1/2 ! 0.5 ... 99.5 |
||
mean = SUM(vec) / LEN(vec) ! 50 |
mean = SUM(vec) / LEN(vec) ! 50 |
||
END </ |
END </syntaxhighlight> |
||
=={{header|Hy}}== |
=={{header|Hy}}== |
||
Returns <tt>None</tt> if the input is of length zero. |
Returns <tt>None</tt> if the input is of length zero. |
||
< |
<syntaxhighlight lang="clojure">(defn arithmetic-mean [xs] |
||
(if xs |
(if xs |
||
(/ (sum xs) (len xs))))</ |
(/ (sum xs) (len xs))))</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
< |
<syntaxhighlight lang="icon">procedure main(args) |
||
every (s := 0) +:= !args |
every (s := 0) +:= !args |
||
write((real(s)/(0 ~= *args)) | 0) |
write((real(s)/(0 ~= *args)) | 0) |
||
end</ |
end</syntaxhighlight> |
||
Sample outputs: |
Sample outputs: |
||
Line 1,329: | Line 1,778: | ||
If truly only the mean is wanted, one could use |
If truly only the mean is wanted, one could use |
||
< |
<syntaxhighlight lang="idl">x = [3,1,4,1,5,9] |
||
print,mean(x)</ |
print,mean(x)</syntaxhighlight> |
||
But <tt>mean()</tt> is just a thin wrapper returning the zeroth element of <tt>moment()</tt> : |
But <tt>mean()</tt> is just a thin wrapper returning the zeroth element of <tt>moment()</tt> : |
||
< |
<syntaxhighlight lang="idl">print,moment(x) |
||
; ==> |
; ==> |
||
3.83333 8.96667 0.580037 -1.25081</ |
3.83333 8.96667 0.580037 -1.25081</syntaxhighlight> |
||
which are mean, variance, skewness and kurtosis. |
which are mean, variance, skewness and kurtosis. |
||
Line 1,344: | Line 1,793: | ||
=={{header|J}}== |
=={{header|J}}== |
||
< |
<syntaxhighlight lang="j">mean=: +/ % #</syntaxhighlight> |
||
That is, sum divided by the number of items. The verb also works on higher-ranked arrays. For example: |
That is, sum divided by the number of items. The verb also works on higher-ranked arrays. For example: |
||
< |
<syntaxhighlight lang="j"> mean 3 1 4 1 5 9 |
||
3.83333 |
3.83333 |
||
mean $0 NB. $0 is a zero-length vector |
mean $0 NB. $0 is a zero-length vector |
||
Line 1,354: | Line 1,803: | ||
x=: 20 4 ?@$ 0 NB. a 20-by-4 table of random (0,1) numbers |
x=: 20 4 ?@$ 0 NB. a 20-by-4 table of random (0,1) numbers |
||
mean x |
mean x |
||
0.58243 0.402948 0.477066 0.511155</ |
0.58243 0.402948 0.477066 0.511155</syntaxhighlight> |
||
The computation can also be written as a loop. It is shown here for comparison only and is highly non-preferred compared to the version above. |
The computation can also be written as a loop. It is shown here for comparison only and is highly non-preferred compared to the version above. |
||
< |
<syntaxhighlight lang="j">mean1=: 3 : 0 |
||
z=. 0 |
z=. 0 |
||
for_i. i.#y do. z=. z+i{y end. |
for_i. i.#y do. z=. z+i{y end. |
||
Line 1,368: | Line 1,817: | ||
0 |
0 |
||
mean1 x |
mean1 x |
||
0.58243 0.402948 0.477066 0.511155</ |
0.58243 0.402948 0.477066 0.511155</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
{{works with|Java|1.5+}} |
{{works with|Java|1.5+}} |
||
<syntaxhighlight lang="java5">public static double avg(double... arr) { |
|||
Assume the numbers are in a double array called "nums". |
|||
double sum = 0.0; |
|||
<lang java5>... |
|||
double |
for (double x : arr) { |
||
sum += x; |
|||
for(double i : nums){ |
|||
} |
|||
return sum / arr.length; |
|||
} |
|||
}</syntaxhighlight> |
|||
System.out.println("The mean is: " + ((nums.length != 0) ? (sum / nums.length) : 0)); |
|||
...</lang> |
|||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
Line 1,386: | Line 1,834: | ||
===ES5=== |
===ES5=== |
||
< |
<syntaxhighlight lang="javascript">function mean(array) |
||
{ |
{ |
||
var sum = 0, i; |
var sum = 0, i; |
||
Line 1,397: | Line 1,845: | ||
alert( mean( [1,2,3,4,5] ) ); // 3 |
alert( mean( [1,2,3,4,5] ) ); // 3 |
||
alert( mean( [] ) ); // 0</ |
alert( mean( [] ) ); // 0</syntaxhighlight> |
||
Using the native function `.forEach()`: |
Using the native function `.forEach()`: |
||
< |
<syntaxhighlight lang="javascript">function mean(array) { |
||
var sum = 0; |
var sum = 0; |
||
array.forEach(function(value){ |
array.forEach(function(value){ |
||
Line 1,408: | Line 1,856: | ||
} |
} |
||
alert( mean( [1,2,3,4,5] ) ); // 3</ |
alert( mean( [1,2,3,4,5] ) ); // 3</syntaxhighlight> |
||
Using the native function `.reduce()`: |
Using the native function `.reduce()`: |
||
< |
<syntaxhighlight lang="javascript">function mean(array) { |
||
return !array.length ? 0 |
return !array.length ? 0 |
||
: array.reduce(function(pre, cur, i) { |
: array.reduce(function(pre, cur, i) { |
||
Line 1,420: | Line 1,868: | ||
alert( mean( [1,2,3,4,5] ) ); // 3 |
alert( mean( [1,2,3,4,5] ) ); // 3 |
||
alert( mean( [] ) ); // 0 |
alert( mean( [] ) ); // 0 |
||
</syntaxhighlight> |
|||
</lang> |
|||
Extending the `Array` prototype: |
Extending the `Array` prototype: |
||
< |
<syntaxhighlight lang="javascript">Array.prototype.mean = function() { |
||
return !this.length ? 0 |
return !this.length ? 0 |
||
: this.reduce(function(pre, cur, i) { |
: this.reduce(function(pre, cur, i) { |
||
Line 1,432: | Line 1,880: | ||
alert( [1,2,3,4,5].mean() ); // 3 |
alert( [1,2,3,4,5].mean() ); // 3 |
||
alert( [].mean() ); // 0 |
alert( [].mean() ); // 0 |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{libheader|Functional}} |
{{libheader|Functional}} |
||
< |
<syntaxhighlight lang="javascript">function mean(a) |
||
{ |
{ |
||
return a.length ? Functional.reduce('+', 0, a) / a.length : 0; |
return a.length ? Functional.reduce('+', 0, a) / a.length : 0; |
||
}</ |
}</syntaxhighlight> |
||
===ES6=== |
===ES6=== |
||
< |
<syntaxhighlight lang="javascript">(sample => { |
||
// mean :: [Num] => (Num | NaN) |
// mean :: [Num] => (Num | NaN) |
||
Line 1,457: | Line 1,905: | ||
return mean(sample); |
return mean(sample); |
||
})([1, 2, 3, 4, 5, 6, 7, 8, 9]);</ |
})([1, 2, 3, 4, 5, 6, 7, 8, 9]);</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<syntaxhighlight lang="javascript">5</syntaxhighlight> |
|||
<lang JavaScript>5</lang> |
|||
=={{header|Joy}}== |
|||
<syntaxhighlight lang="joy">DEFINE avg == dup 0. [+] fold swap size 1 max /.</syntaxhighlight> |
|||
=={{header|jq}}== |
=={{header|jq}}== |
||
The mean of an array of numbers can be computed by simply writing |
The mean of an array of numbers can be computed by simply writing |
||
<lang |
<syntaxhighlight lang="jq">add/length</syntaxhighlight> |
||
This definition raises an error condition if the array is empty, so it may make sense to define '''mean''' as follows, '''null''' being jq's null value: |
This definition raises an error condition if the array is empty, so it may make sense to define '''mean''' as follows, '''null''' being jq's null value: |
||
< |
<syntaxhighlight lang="jq">def mean: if length == 0 then null |
||
else add/length |
else add/length |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
Julia's built-in mean function accepts AbstractArrays (vector, matrix, etc.) |
Julia's built-in mean function accepts AbstractArrays (vector, matrix, etc.) |
||
< |
<syntaxhighlight lang="julia">julia> using Statistics; mean([1,2,3]) |
||
2.0 |
2.0 |
||
julia> mean(1:10) |
julia> mean(1:10) |
||
5.5 |
5.5 |
||
julia> mean([]) |
julia> mean([]) |
||
ERROR: mean of empty collection undefined: []</ |
ERROR: mean of empty collection undefined: []</syntaxhighlight> |
||
=={{header|K}}== |
=={{header|K}}== |
||
< |
<syntaxhighlight lang="k"> mean: {(+/x)%#x} |
||
mean 1 2 3 5 7 |
mean 1 2 3 5 7 |
||
3.6 |
3.6 |
||
mean@!0 / empty array |
mean@!0 / empty array |
||
0.0</ |
0.0</syntaxhighlight> |
||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
Kotlin has builtin functions for some collection types. |
Kotlin has builtin functions for some collection types. |
||
Example: |
Example: |
||
< |
<syntaxhighlight lang="scala">fun main(args: Array<String>) { |
||
val nums = doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0) |
val nums = doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0) |
||
println("average = %f".format(nums.average())) |
println("average = %f".format(nums.average())) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|KQL}}== |
|||
<syntaxhighlight lang="kql"> |
|||
let dataset = datatable(values:real)[ |
|||
1, 1.5, 3, 5, 6.5]; |
|||
dataset|summarize avg(values) |
|||
</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
avg_values |
|||
3.4 |
|||
</pre> |
|||
=={{header|LabVIEW}}== |
=={{header|LabVIEW}}== |
||
{{VI solution|LabVIEW_Averages_Arithmetic_mean.png}} |
{{VI solution|LabVIEW_Averages_Arithmetic_mean.png}} |
||
=={{header|Lambdatalk}}== |
|||
<syntaxhighlight lang="scheme"> |
|||
{def mean |
|||
{lambda {:s} |
|||
{if {S.empty? :s} |
|||
then 0 |
|||
else {/ {+ :s} {S.length :s}}}}} |
|||
{mean {S.serie 0 1000}} |
|||
-> 500 |
|||
</syntaxhighlight> |
|||
=={{header|langur}}== |
|||
The built-in mean() function works with an array, hash, or range of numbers. |
|||
We could use fold() to write a function that takes an array and calculates the mean. |
|||
<syntaxhighlight lang="langur">val umean = fn x:fold(fn{+}, x) / len(x) |
|||
writeln " custom: ", umean([7, 3, 12]) |
|||
writeln "built-in: ", mean([7, 3, 12]) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> custom: 7.333333333333333333333333333333333 |
|||
built-in: 7.333333333333333333333333333333333</pre> |
|||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
< |
<syntaxhighlight lang="lasso">define average(a::array) => { |
||
not #a->size ? return 0 |
not #a->size ? return 0 |
||
local(x = 0.0) |
local(x = 0.0) |
||
Line 1,506: | Line 1,999: | ||
} |
} |
||
average(array(1,2,5,17,7.4)) //6.48</ |
average(array(1,2,5,17,7.4)) //6.48</syntaxhighlight> |
||
=={{header|LFE}}== |
=={{header|LFE}}== |
||
Line 1,512: | Line 2,005: | ||
=== 1-Arity === |
=== 1-Arity === |
||
< |
<syntaxhighlight lang="lisp"> |
||
(defun mean (data) |
(defun mean (data) |
||
(/ (lists:sum data) |
(/ (lists:sum data) |
||
(length data))) |
(length data))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Usage: |
Usage: |
||
< |
<syntaxhighlight lang="lisp">> (mean '(1 1)) |
||
1.0 |
1.0 |
||
> (mean '(1 2)) |
> (mean '(1 2)) |
||
Line 1,526: | Line 2,019: | ||
6.0 |
6.0 |
||
> (mean '(6 12 18 24 30 36 42 48 54 60 66 72 78)) |
> (mean '(6 12 18 24 30 36 42 48 54 60 66 72 78)) |
||
42.0</ |
42.0</syntaxhighlight> |
||
=== n-Arity === |
=== n-Arity === |
||
Line 1,532: | Line 2,025: | ||
Functions in LFE (and Erlang) have set arity, but macros can be used to provide the same use as n-arity functions: |
Functions in LFE (and Erlang) have set arity, but macros can be used to provide the same use as n-arity functions: |
||
< |
<syntaxhighlight lang="lisp">(defmacro mean args |
||
`(/ (lists:sum ,args) |
`(/ (lists:sum ,args) |
||
,(length args)))</ |
,(length args)))</syntaxhighlight> |
||
Usage: |
Usage: |
||
< |
<syntaxhighlight lang="lisp">> (mean 42) |
||
42.0 |
42.0 |
||
> (mean 18 66) |
> (mean 18 66) |
||
42.0 |
42.0 |
||
> (mean 6 12 18 24 30 36 42 48 54 60 66 72 78) |
> (mean 6 12 18 24 30 36 42 48 54 60 66 72 78) |
||
42.0</ |
42.0</syntaxhighlight> |
||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
< |
<syntaxhighlight lang="lb">total=17 |
||
dim nums(total) |
dim nums(total) |
||
for i = 1 to total |
for i = 1 to total |
||
Line 1,557: | Line 2,050: | ||
if total=0 then mean=0 else mean=sum/total |
if total=0 then mean=0 else mean=sum/total |
||
print "Arithmetic mean: ";mean |
print "Arithmetic mean: ";mean |
||
</ |
</syntaxhighlight> |
||
=={{header|Limbo}}== |
|||
<syntaxhighlight lang="limbo">implement Command; |
|||
include "sys.m"; |
|||
sys: Sys; |
|||
include "draw.m"; |
|||
include "sh.m"; |
|||
init(nil: ref Draw->Context, nil: list of string) |
|||
{ |
|||
sys = load Sys Sys->PATH; |
|||
a := array[] of {1.0, 2.0, 500.0, 257.0}; |
|||
sys->print("mean of a: %f\n", getmean(a)); |
|||
} |
|||
getmean(a: array of real): real |
|||
{ |
|||
n: real = 0.0; |
|||
for (i := 0; i < len a; i++) |
|||
n += a[i]; |
|||
return n / (real len a); |
|||
}</syntaxhighlight> |
|||
=={{header|Lingo}}== |
|||
<syntaxhighlight lang="lingo">-- v can be (2D) point, (3D) vector or list of integers/floats |
|||
on mean (v) |
|||
case ilk(v) of |
|||
#point: cnt = 2 |
|||
#vector: cnt = 3 |
|||
#list: cnt = v.count |
|||
otherwise: return |
|||
end case |
|||
sum = 0 |
|||
repeat with i = 1 to cnt |
|||
sum = sum + v[i] |
|||
end repeat |
|||
return float(sum)/cnt |
|||
end</syntaxhighlight> |
|||
<syntaxhighlight lang="lingo">put mean(point(1, 2.5)) |
|||
-- 1.7500 |
|||
put mean(vector(1.2, 4.7, 5.6)) |
|||
-- 3.8333 |
|||
put mean([6,12,18,24,30,36,42,48,54,60,66,72,78]) |
|||
-- 42.0000</syntaxhighlight> |
|||
=={{header|LiveCode}}== |
=={{header|LiveCode}}== |
||
Livecode provides arithmeticMean (avg, average) built-in. |
Livecode provides arithmeticMean (avg, average) built-in. |
||
< |
<syntaxhighlight lang="livecode">average(1,2,3,4,5) -- 3 |
||
average(empty) -- 0</ |
average(empty) -- 0</syntaxhighlight> |
||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
< |
<syntaxhighlight lang="logo">to average :l |
||
if empty? :l [output 0] |
if empty? :l [output 0] |
||
output quotient apply "sum :l count :l |
output quotient apply "sum :l count :l |
||
end |
end |
||
print average [1 2 3 4] ; 2.5</ |
print average [1 2 3 4] ; 2.5</syntaxhighlight> |
||
=={{header|Logtalk}}== |
=={{header|Logtalk}}== |
||
Logtalk's standard library provides an arithmetic average predicate but we ignore it here. Representing a vector using a list: |
Logtalk's standard library provides an arithmetic average predicate but we ignore it here. Representing a vector using a list: |
||
< |
<syntaxhighlight lang="logtalk"> |
||
:- object(averages). |
:- object(averages). |
||
Line 1,591: | Line 2,133: | ||
:- end_object. |
:- end_object. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Sample output: |
Sample output: |
||
< |
<syntaxhighlight lang="text"> |
||
| ?- averages::arithmetic([1,2,3,4,5,6,7,8,9,10], Mean). |
| ?- averages::arithmetic([1,2,3,4,5,6,7,8,9,10], Mean). |
||
Mean = 5.5 |
Mean = 5.5 |
||
yes |
yes |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|LSL}}== |
=={{header|LSL}}== |
||
< |
<syntaxhighlight lang="lsl">integer MAX_ELEMENTS = 10; |
||
integer MAX_VALUE = 100; |
integer MAX_VALUE = 100; |
||
default { |
default { |
||
Line 1,621: | Line 2,163: | ||
llOwnerSay(" Sum Squares: "+(string)llListStatistics(LIST_STAT_SUM_SQUARES, lst)); |
llOwnerSay(" Sum Squares: "+(string)llListStatistics(LIST_STAT_SUM_SQUARES, lst)); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 1,638: | Line 2,180: | ||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua">function mean (numlist) |
||
if type(numlist) ~= 'table' then return numlist end |
if type(numlist) ~= 'table' then return numlist end |
||
num = 0 |
num = 0 |
||
Line 1,645: | Line 2,187: | ||
end |
end |
||
print (mean({3,1,4,1,5,9}))</ |
print (mean({3,1,4,1,5,9}))</syntaxhighlight> |
||
=={{header|Lucid}}== |
=={{header|Lucid}}== |
||
< |
<syntaxhighlight lang="lucid">avg(x) |
||
where |
where |
||
sum = first(x) fby sum + next(x); |
sum = first(x) fby sum + next(x); |
||
n = 1 fby n + 1; |
n = 1 fby n + 1; |
||
avg = sum / n; |
avg = sum / n; |
||
end</ |
end</syntaxhighlight> |
||
=={{header|M4}}== |
=={{header|M4}}== |
||
Line 1,662: | Line 2,204: | ||
directly, but it is a little bit clearer to keep them separated. |
directly, but it is a little bit clearer to keep them separated. |
||
< |
<syntaxhighlight lang="m4">define(`extractdec', `ifelse(eval(`$1%100 < 10'),1,`0',`')eval($1%100)')dnl |
||
define(`fmean', `eval(`($2/$1)/100').extractdec(eval(`$2/$1'))')dnl |
define(`fmean', `eval(`($2/$1)/100').extractdec(eval(`$2/$1'))')dnl |
||
define(`mean', `rmean(`$#', $@)')dnl |
define(`mean', `rmean(`$#', $@)')dnl |
||
define(`rmean', `ifelse(`$3', `', `fmean($1,$2)',dnl |
define(`rmean', `ifelse(`$3', `', `fmean($1,$2)',dnl |
||
`rmean($1, eval($2+$3), shift(shift(shift($@))))')')dnl</ |
`rmean($1, eval($2+$3), shift(shift(shift($@))))')')dnl</syntaxhighlight> |
||
< |
<syntaxhighlight lang="m4">mean(0,100,200,300,400,500,600,700,800,900,1000)</syntaxhighlight> |
||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
This version accepts any indexable structure, including numeric arrays. We use a call to the "environment variable" (dynamically scoped global) "Normalizer" to provide normalization of symbolic expressions. This can be set by the caller to adjust the strength of normalization desired. |
This version accepts any indexable structure, including numeric arrays. We use a call to the "environment variable" (dynamically scoped global) "Normalizer" to provide normalization of symbolic expressions. This can be set by the caller to adjust the strength of normalization desired. |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
mean := proc( a :: indexable ) |
mean := proc( a :: indexable ) |
||
local i; |
local i; |
||
Normalizer( add( i, i in a ) / numelems( a ) ) |
Normalizer( add( i, i in a ) / numelems( a ) ) |
||
end proc: |
end proc: |
||
</syntaxhighlight> |
|||
</lang> |
|||
For example: |
For example: |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
> mean( { 1/2, 2/3, 3/4, 4/5, 5/6 } ); # set |
> mean( { 1/2, 2/3, 3/4, 4/5, 5/6 } ); # set |
||
71 |
71 |
||
Line 1,700: | Line 2,242: | ||
> mean([]); # empty argument causes an exception to be raised. |
> mean([]); # empty argument causes an exception to be raised. |
||
Error, (in mean) numeric exception: division by zero |
Error, (in mean) numeric exception: division by zero |
||
</syntaxhighlight> |
|||
</lang> |
|||
A slightly different design computes the mean of all its arguments, instead of requiring a single container argument. This seems a little more Maple-like for a general purpose utility. |
A slightly different design computes the mean of all its arguments, instead of requiring a single container argument. This seems a little more Maple-like for a general purpose utility. |
||
< |
<syntaxhighlight lang="maple">mean := () -> Normalizer( `+`( args ) / nargs ):</syntaxhighlight> |
||
This can be called as in the following examples. |
This can be called as in the following examples. |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
> mean( 1, 2, 3, 4, 5 ); |
> mean( 1, 2, 3, 4, 5 ); |
||
3 |
3 |
||
Line 1,715: | Line 2,257: | ||
> mean(); # again, an exception is raised |
> mean(); # again, an exception is raised |
||
Error, (in mean) numeric exception: division by zero |
Error, (in mean) numeric exception: division by zero |
||
</syntaxhighlight> |
|||
</lang> |
|||
If desired, we can add argument type-checking as follows. |
If desired, we can add argument type-checking as follows. |
||
< |
<syntaxhighlight lang="maple">mean := ( s :: seq(algebraic) ) -> Normalizer( `+`( args ) / nargs ):</syntaxhighlight> |
||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
Modify the built-in Mean function to give 0 for empty vectors (lists in Mathematica): |
Modify the built-in Mean function to give 0 for empty vectors (lists in Mathematica): |
||
< |
<syntaxhighlight lang="mathematica">Unprotect[Mean]; |
||
Mean[{}] := 0</ |
Mean[{}] := 0</syntaxhighlight> |
||
Examples: |
Examples: |
||
< |
<syntaxhighlight lang="mathematica">Mean[{3,4,5}] |
||
Mean[{3.2,4.5,5.9}] |
Mean[{3.2,4.5,5.9}] |
||
Mean[{-4, 1.233}] |
Mean[{-4, 1.233}] |
||
Mean[{}] |
Mean[{}] |
||
Mean[{1/2,1/3,1/4,1/5}] |
Mean[{1/2,1/3,1/4,1/5}] |
||
Mean[{a,c,Pi,-3,a}]</ |
Mean[{a,c,Pi,-3,a}]</syntaxhighlight> |
||
gives (a set of integers gives back an integer or a rational, a set of floats gives back a float, a set of rationals gives a rational back, a list of symbols and numbers keeps the symbols exact and a mix of exact and approximate numbers gives back an approximate number): |
gives (a set of integers gives back an integer or a rational, a set of floats gives back a float, a set of rationals gives a rational back, a list of symbols and numbers keeps the symbols exact and a mix of exact and approximate numbers gives back an approximate number): |
||
< |
<syntaxhighlight lang="mathematica">4 |
||
4.53333 |
4.53333 |
||
-1.3835 |
-1.3835 |
||
0 |
0 |
||
77/240 |
77/240 |
||
1/5 (-3+2 a+c+Pi)</ |
1/5 (-3+2 a+c+Pi)</syntaxhighlight> |
||
=={{header|Mathprog}}== |
=={{header|Mathprog}}== |
||
Line 1,748: | Line 2,290: | ||
To make it more interesting I find the Arithmectic Mean of more than a million Integers. |
To make it more interesting I find the Arithmectic Mean of more than a million Integers. |
||
<lang> |
<syntaxhighlight lang="text"> |
||
/*Arithmetic Mean of a large number of Integers |
/*Arithmetic Mean of a large number of Integers |
||
- or - solve a very large constraint matrix |
- or - solve a very large constraint matrix |
||
Line 1,773: | Line 2,315: | ||
end; |
end; |
||
</syntaxhighlight> |
|||
</lang> |
|||
When run this produces: |
When run this produces: |
||
<lang> |
<syntaxhighlight lang="text"> |
||
GLPSOL: GLPK LP/MIP Solver, v4.47 |
GLPSOL: GLPK LP/MIP Solver, v4.47 |
||
Parameter(s) specified in the command line: |
Parameter(s) specified in the command line: |
||
Line 1,800: | Line 2,342: | ||
The arithmetic mean of the integers from 1 to 1048575 is 524288.000000 |
The arithmetic mean of the integers from 1 to 1048575 is 524288.000000 |
||
Model has been successfully processed |
Model has been successfully processed |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|MATLAB}}== |
=={{header|MATLAB}}== |
||
< |
<syntaxhighlight lang="matlab">function meanValue = findmean(setOfValues) |
||
meanValue = mean(setOfValues); |
meanValue = mean(setOfValues); |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">load("descriptive"); |
||
mean([2, 7, 11, 17]);</ |
mean([2, 7, 11, 17]);</syntaxhighlight> |
||
=={{header|MAXScript}}== |
=={{header|MAXScript}}== |
||
< |
<syntaxhighlight lang="maxscript">fn mean data = |
||
( |
( |
||
total = 0 |
total = 0 |
||
Line 1,822: | Line 2,364: | ||
) |
) |
||
print (mean #(3, 1, 4, 1, 5, 9))</ |
print (mean #(3, 1, 4, 1, 5, 9))</syntaxhighlight> |
||
=={{header|Mercury}}== |
=={{header|Mercury}}== |
||
< |
<syntaxhighlight lang="mercury">:- module arithmetic_mean. |
||
:- interface. |
:- interface. |
||
Line 1,844: | Line 2,386: | ||
mean(Ns @ [_ | _]) = foldl((+), Ns, 0.0) / float(length(Ns)). |
mean(Ns @ [_ | _]) = foldl((+), Ns, 0.0) / float(length(Ns)). |
||
:- end_module arithmetic_mean.</ |
:- end_module arithmetic_mean.</syntaxhighlight> |
||
Alternatively, we could use inst subtyping to ensure we get a compilation error if the |
Alternatively, we could use inst subtyping to ensure we get a compilation error if the |
||
mean function is called with an empty list. |
mean function is called with an empty list. |
||
< |
<syntaxhighlight lang="mercury">:- func mean(list(float)::in(non_empty_list)) = (float::out). |
||
mean(Ns) = foldl((+), Ns, 0.0) / float(length(Ns)).</ |
mean(Ns) = foldl((+), Ns, 0.0) / float(length(Ns)).</syntaxhighlight> |
||
=={{header|min}}== |
|||
Returns <code>nan</code> for an empty quotation. |
|||
{{works with|min|0.37.0}} |
|||
<syntaxhighlight lang="min">(2 3 5) avg puts!</syntaxhighlight> |
|||
{{out}} |
|||
<pre>3.333333333333333</pre> |
|||
=={{header|MiniScript}}== |
|||
<syntaxhighlight lang="miniscript">arr = [ 1, 3, 7, 8, 9, 1 ] |
|||
avg = function(arr) |
|||
avgNum = 0 |
|||
for num in arr |
|||
avgNum = avgNum + num |
|||
end for |
|||
return avgNum / arr.len |
|||
end function |
|||
print avg(arr)</syntaxhighlight> |
|||
=={{header|МК-61/52}}== |
=={{header|МК-61/52}}== |
||
<lang>0 П0 П1 С/П ИП0 ИП1 * + ИП1 1 |
<syntaxhighlight lang="text">0 П0 П1 С/П ИП0 ИП1 * + ИП1 1 |
||
+ П1 / П0 БП 03</ |
+ П1 / П0 БП 03</syntaxhighlight> |
||
''Instruction:'' В/О С/П Number С/П Number ... |
''Instruction:'' В/О С/П Number С/П Number ... |
||
Line 1,862: | Line 2,425: | ||
=={{header|Modula-2}}== |
=={{header|Modula-2}}== |
||
< |
<syntaxhighlight lang="modula2">PROCEDURE Avg; |
||
VAR avg : REAL; |
VAR avg : REAL; |
||
Line 1,871: | Line 2,434: | ||
InOut.WriteReal (avg, 8, 2); |
InOut.WriteReal (avg, 8, 2); |
||
InOut.WriteLn |
InOut.WriteLn |
||
END Avg;</ |
END Avg;</syntaxhighlight> |
||
OR |
OR |
||
< |
<syntaxhighlight lang="modula2">PROCEDURE Average (Data : ARRAY OF REAL; Samples : CARDINAL) : REAL; |
||
(* Calculate the average over 'Samples' values, stored in array 'Data'. *) |
(* Calculate the average over 'Samples' values, stored in array 'Data'. *) |
||
Line 1,886: | Line 2,449: | ||
END; |
END; |
||
RETURN sum / FLOAT(Samples) |
RETURN sum / FLOAT(Samples) |
||
END Average;</ |
END Average;</syntaxhighlight> |
||
=={{header|MUMPS}}== |
=={{header|MUMPS}}== |
||
< |
<syntaxhighlight lang="mumps">MEAN(X) |
||
;X is assumed to be a list of numbers separated by "^" |
;X is assumed to be a list of numbers separated by "^" |
||
QUIT:'$DATA(X) "No data" |
QUIT:'$DATA(X) "No data" |
||
Line 1,895: | Line 2,459: | ||
SET S=0,I=1 |
SET S=0,I=1 |
||
FOR QUIT:I>$L(X,"^") SET S=S+$P(X,"^",I),I=I+1 |
FOR QUIT:I>$L(X,"^") SET S=S+$P(X,"^",I),I=I+1 |
||
QUIT (S/$L(X,"^"))</ |
QUIT (S/$L(X,"^"))</syntaxhighlight> |
||
<pre>USER>W $$MEAN^ROSETTA |
<pre>USER>W $$MEAN^ROSETTA |
||
No data |
No data |
||
Line 1,905: | Line 2,469: | ||
5.75 |
5.75 |
||
</pre> |
</pre> |
||
=={{header|Nanoquery}}== |
|||
<syntaxhighlight lang="nanoquery">def sum(lst) |
|||
sum = 0 |
|||
for n in lst |
|||
sum += n |
|||
end |
|||
return sum |
|||
end |
|||
def average(x) |
|||
return sum(x) / len(x) |
|||
end</syntaxhighlight> |
|||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
< |
<syntaxhighlight lang="nemerle">using System; |
||
using System.Console; |
using System.Console; |
||
using Nemerle.Collections; |
using Nemerle.Collections; |
||
Line 1,923: | Line 2,500: | ||
WriteLine("Mean of [1 .. 10]: {0}", ArithmeticMean($[1 .. 10])); |
WriteLine("Mean of [1 .. 10]: {0}", ArithmeticMean($[1 .. 10])); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
options replace format comments java crossref symbols nobinary |
options replace format comments java crossref symbols nobinary |
||
Line 1,977: | Line 2,554: | ||
] |
] |
||
return vectors |
return vectors |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Output:''' |
'''Output:''' |
||
<pre> |
<pre> |
||
Line 2,001: | Line 2,578: | ||
=={{header|NewLISP}}== |
=={{header|NewLISP}}== |
||
< |
<syntaxhighlight lang="newlisp">(define (Mean Lst) |
||
(if (empty? Lst) |
(if (empty? Lst) |
||
0 |
0 |
||
Line 2,007: | Line 2,584: | ||
(Mean (sequence 1 1000))-> 500 |
(Mean (sequence 1 1000))-> 500 |
||
(Mean '()) -> 0</ |
(Mean '()) -> 0</syntaxhighlight> |
||
=={{header|Nial}}== |
=={{header|Nial}}== |
||
in the standard way, mean is |
in the standard way, mean is |
||
< |
<syntaxhighlight lang="nial">mean is / [sum, tally] |
||
mean 6 2 4 |
mean 6 2 4 |
||
= 4</ |
= 4</syntaxhighlight> |
||
but it fails with 0 length vectors. so using a tally with a minimum value 1 |
but it fails with 0 length vectors. so using a tally with a minimum value 1 |
||
< |
<syntaxhighlight lang="nial">dtally is recur [ empty rest, 1 first, 1 first, plus, rest ] |
||
mean is / [sum, dtally] |
mean is / [sum, dtally] |
||
mean [] |
mean [] |
||
=0</ |
=0</syntaxhighlight> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="nim">import strutils |
||
proc mean(xs): float = |
proc mean(xs: openArray[float]): float = |
||
for x in xs: |
for x in xs: |
||
result += x |
result += x |
||
Line 2,035: | Line 2,612: | ||
for i in 0..5: |
for i in 0..5: |
||
echo "mean of first ", v.len, " = ", formatFloat(mean(v), precision = 0) |
echo "mean of first ", v.len, " = ", formatFloat(mean(v), precision = 0) |
||
v.setLen(v.high)</ |
if v.len > 0: v.setLen(v.high)</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>mean of first 5 = 2.372 |
<pre>mean of first 5 = 2.372 |
||
Line 2,042: | Line 2,619: | ||
mean of first 2 = 1.5 |
mean of first 2 = 1.5 |
||
mean of first 1 = 1 |
mean of first 1 = 1 |
||
mean of first 0 = - |
mean of first 0 = -1.#IND</pre> |
||
=={{header|Niue}}== |
=={{header|Niue}}== |
||
<syntaxhighlight lang="niue"> |
|||
<lang Niue> |
|||
[ [ , len 1 - at ! ] len 3 - times swap , ] 'map ; ( a Lisp like map, to sum the stack ) |
[ [ , len 1 - at ! ] len 3 - times swap , ] 'map ; ( a Lisp like map, to sum the stack ) |
||
[ len 'n ; [ + ] 0 n swap-at map n / ] 'avg ; |
[ len 'n ; [ + ] 0 n swap-at map n / ] 'avg ; |
||
Line 2,053: | Line 2,630: | ||
3.4 2.3 .01 2.0 2.1 avg . |
3.4 2.3 .01 2.0 2.1 avg . |
||
=> 1.9619999999999997 |
=> 1.9619999999999997 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Oberon-2}}== |
=={{header|Oberon-2}}== |
||
Oxford Oberon-2 |
Oxford Oberon-2 |
||
< |
<syntaxhighlight lang="oberon2"> |
||
MODULE AvgMean; |
MODULE AvgMean; |
||
IMPORT Out; |
IMPORT Out; |
||
Line 2,086: | Line 2,664: | ||
Out.Fixed(Avg(ary),4,2);Out.Ln |
Out.Fixed(Avg(ary),4,2);Out.Ln |
||
END AvgMean. |
END AvgMean. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
14.55 |
14.55 |
||
</pre> |
</pre> |
||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck"> |
||
function : native : PrintAverage(values : FloatVector) ~ Nil { |
function : native : PrintAverage(values : FloatVector) ~ Nil { |
||
values->Average()->PrintLine(); |
values->Average()->PrintLine(); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
These functions return a float: |
These functions return a float: |
||
< |
<syntaxhighlight lang="ocaml">let mean_floats = function |
||
| [] -> 0. |
| [] -> 0. |
||
| xs -> List.fold_left (+.) 0. xs /. float_of_int (List.length xs) |
| xs -> List.fold_left (+.) 0. xs /. float_of_int (List.length xs) |
||
let mean_ints xs = mean_floats (List.map float_of_int xs)</ |
let mean_ints xs = mean_floats (List.map float_of_int xs)</syntaxhighlight> |
||
the previous code is easier to read and understand, though if you wish |
the previous code is easier to read and understand, though if you wish |
||
Line 2,117: | Line 2,696: | ||
would rather be handled by an exception. |
would rather be handled by an exception. |
||
< |
<syntaxhighlight lang="ocaml">let mean_floats xs = |
||
if xs = [] then |
if xs = [] then |
||
invalid_arg "empty list" |
invalid_arg "empty list" |
||
Line 2,140: | Line 2,719: | ||
in |
in |
||
(float total /. length) |
(float total /. length) |
||
;;</ |
;;</syntaxhighlight> |
||
=={{header|Octave}}== |
=={{header|Octave}}== |
||
Line 2,146: | Line 2,725: | ||
GNU Octave has a <tt>mean</tt> function (from statistics package), but it does not handle an empty vector; an implementation that allows that is: |
GNU Octave has a <tt>mean</tt> function (from statistics package), but it does not handle an empty vector; an implementation that allows that is: |
||
< |
<syntaxhighlight lang="octave">function m = omean(l) |
||
if ( numel(l) == 0 ) |
if ( numel(l) == 0 ) |
||
m = 0; |
m = 0; |
||
Line 2,155: | Line 2,734: | ||
disp(omean([])); |
disp(omean([])); |
||
disp(omean([1,2,3]));</ |
disp(omean([1,2,3]));</syntaxhighlight> |
||
If the data contains missing value, encoded as non-a-number: |
If the data contains missing value, encoded as non-a-number: |
||
< |
<syntaxhighlight lang="octave">function m = omean(l) |
||
n = sum(~isnan(l)); |
n = sum(~isnan(l)); |
||
l(isnan(l))=0; |
l(isnan(l))=0; |
||
s = sum(l); |
s = sum(l); |
||
m = s./n; |
m = s./n; |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
<syntaxhighlight lang="oforth">: avg ( x -- avg ) |
|||
Oforth has a avg method. It returs null is the collection is empty |
|||
x sum |
|||
x size dup ifZero: [ 2drop null ] else: [ >float / ] |
|||
<lang Oforth>[1, 2, 2.718, 3, 3.142] avg println |
|||
;</syntaxhighlight> |
|||
[ ] avg println</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
[1, 2, 2.718, 3, 3.142] avg . |
|||
2.372 |
|||
2.372 ok |
|||
null |
|||
[ ] avg . |
|||
null ok |
|||
</pre> |
</pre> |
||
=={{header|ooRexx}}== |
=={{header|ooRexx}}== |
||
<syntaxhighlight lang="oorexx"> |
|||
<lang ooRexx> |
|||
call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1) |
call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1) |
||
call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11) |
call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11) |
||
Line 2,202: | Line 2,783: | ||
end |
end |
||
return sum/numbers~items |
return sum/numbers~items |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 2,220: | Line 2,801: | ||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
A version working on floats: |
A version working on floats: |
||
< |
<syntaxhighlight lang="oz">declare |
||
fun {Mean Xs} |
fun {Mean Xs} |
||
{FoldL Xs Number.'+' 0.0} / {Int.toFloat {Length Xs}} |
{FoldL Xs Number.'+' 0.0} / {Int.toFloat {Length Xs}} |
||
end |
end |
||
in |
in |
||
{Show {Mean [3. 1. 4. 1. 5. 9.]}}</ |
{Show {Mean [3. 1. 4. 1. 5. 9.]}}</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
< |
<syntaxhighlight lang="parigp">avg(v)={ |
||
if(#v,vecsum(v)/#v) |
if(#v,vecsum(v)/#v) |
||
};</ |
};</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
< |
<syntaxhighlight lang="pascal">Program Mean; |
||
function DoMean(vector: array of double): double; |
function DoMean(vector: array of double): double; |
||
Line 2,262: | Line 2,843: | ||
writeln (']'); |
writeln (']'); |
||
writeln('Mean: ', DoMean(vector):10:8); |
writeln('Mean: ', DoMean(vector):10:8); |
||
end.</ |
end.</syntaxhighlight> |
||
Output: |
Output: |
||
Line 2,273: | Line 2,854: | ||
Alternative version using the Math unit: |
Alternative version using the Math unit: |
||
< |
<syntaxhighlight lang="pascal">Program DoMean; |
||
uses math; |
uses math; |
||
const |
const |
||
Line 2,290: | Line 2,871: | ||
mean := sum(vector)/length(vector); |
mean := sum(vector)/length(vector); |
||
writeln('Mean: ', mean:10:8); |
writeln('Mean: ', mean:10:8); |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">sub avg { |
||
@_ or return 0; |
@_ or return 0; |
||
my $sum = 0; |
my $sum = 0; |
||
Line 2,300: | Line 2,881: | ||
} |
} |
||
print avg(qw(3 1 4 1 5 9)), "\n";</ |
print avg(qw(3 1 4 1 5 9)), "\n";</syntaxhighlight> |
||
{{libheader|Data::Average}} |
|||
With module Data::Average. |
|||
(For zero-length arrays, returns the empty list.) |
|||
<lang perl>use Data::Average; |
|||
my $d = Data::Average->new; |
|||
$d->add($_) foreach qw(3 1 4 1 5 9); |
|||
print $d->avg, "\n";</lang> |
|||
=={{header|Perl 6}}== |
|||
{{works with|Rakudo|2015.10-11}} |
|||
<lang perl6>multi mean([]){ Failure.new('mean on empty list is not defined') }; # Failure-objects are lazy exceptions |
|||
multi mean (@a) { ([+] @a) / @a }</lang> |
|||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
<!--<syntaxhighlight lang="phix">(phixonline)--> |
|||
<lang Phix>function mean(sequence s) |
|||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
|||
if length(s)=0 then return 0 end if |
|||
<span style="color: #008080;">function</span> <span style="color: #000000;">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;">if</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: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> |
|||
end function |
|||
<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> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
|||
<span style="color: #0000FF;">?</span> <span style="color: #000000;">mean</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;">5</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">9.5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3.14159</span><span style="color: #0000FF;">})</span> |
|||
<!--</syntaxhighlight>--> |
|||
=={{header|Phixmonti}}== |
|||
? mean({1, 2, 5, -5, -9.5, 3.14159})</lang> |
|||
<syntaxhighlight lang="phixmonti">1 2 5 -5 -9.5 3.14159 stklen tolist |
|||
len swap sum swap / print</syntaxhighlight> |
|||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php">$nums = array(3, 1, 4, 1, 5, 9); |
||
if ($nums) |
if ($nums) |
||
echo array_sum($nums) / count($nums), "\n"; |
echo array_sum($nums) / count($nums), "\n"; |
||
else |
else |
||
echo "0\n";</ |
echo "0\n";</syntaxhighlight> |
||
=={{header|PL/I}}== |
|||
=={{header|Picat}}== |
|||
<lang pli>arithmetic_mean = sum(A)/dimension(A,1);</lang> |
|||
<syntaxhighlight lang="picat">mean([]) = false. |
|||
mean(V) = sum(V) / len(V).</syntaxhighlight> |
|||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(de mean (Lst) |
||
(if (atom Lst) |
(if (atom Lst) |
||
0 |
0 |
||
(/ (apply + Lst) (length Lst)) ) )</ |
(/ (apply + Lst) (length Lst)) ) )</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>: (mean (range 1 1000)) |
<pre>: (mean (range 1 1000)) |
||
-> 500</pre> |
-> 500</pre> |
||
=={{header|PL/I}}== |
|||
<syntaxhighlight lang="pli">arithmetic_mean = sum(A)/dimension(A,1);</syntaxhighlight> |
|||
=={{header|Plain English}}== |
|||
<syntaxhighlight lang="plainenglish">To run: |
|||
Start up. |
|||
Demonstrate finding the arithmetic mean. |
|||
Wait for the escape key. |
|||
Shut down. |
|||
An entry is a thing with a fraction. |
|||
A list is some entries. |
|||
A sum is a fraction. |
|||
A mean is a fraction. |
|||
To demonstrate finding the arithmetic mean: |
|||
Create an example list. |
|||
Write "A list: " then the example list on the console. |
|||
Find a mean of the example list. |
|||
Write "The list's mean: " then the mean on the console. |
|||
Destroy the example list. |
|||
To add a fraction to a list: |
|||
Allocate memory for an entry. |
|||
Put the fraction into the entry's fraction. |
|||
Append the entry to the list. |
|||
To create an example list: |
|||
Add 1/1 to the example list. |
|||
Add 2/1 to the example list. |
|||
Add 5-1/3 to the example list. |
|||
Add 7-1/2 to the example list. |
|||
To find a sum of a list: |
|||
Put 0 into the sum. |
|||
Get an entry from the list. |
|||
Loop. |
|||
If the entry is nil, exit. |
|||
Add the entry's fraction to the sum. |
|||
Put the entry's next into the entry. |
|||
Repeat. |
|||
To find a mean of a list: |
|||
Find a sum of the list. |
|||
Put the sum divided by the list's count into the mean. |
|||
To convert a list to a string: |
|||
Get an entry from the list. |
|||
Loop. |
|||
If the entry is nil, break. |
|||
Append the entry's fraction to the string. |
|||
If the entry's next is not nil, append ", " to the string. |
|||
Put the entry's next into the entry. |
|||
Repeat.</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
A list: 1, 2, 5-1/3, 7-1/2 |
|||
The list's mean: 3-23/24 |
|||
</pre> |
|||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
< |
<syntaxhighlight lang="pop11">define mean(v); |
||
lvars n = length(v), i, s = 0; |
lvars n = length(v), i, s = 0; |
||
if n = 0 then |
if n = 0 then |
||
Line 2,355: | Line 2,991: | ||
endif; |
endif; |
||
return(s/n); |
return(s/n); |
||
enddefine;</ |
enddefine;</syntaxhighlight> |
||
=={{header|PostScript}}== |
=={{header|PostScript}}== |
||
<lang> |
<syntaxhighlight lang="text"> |
||
/findmean{ |
/findmean{ |
||
/x exch def |
/x exch def |
||
Line 2,374: | Line 3,010: | ||
sum == |
sum == |
||
}def |
}def |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{libheader|initlib}} |
{{libheader|initlib}} |
||
{{works with|Ghostscript}} |
{{works with|Ghostscript}} |
||
< |
<syntaxhighlight lang="postscript"> |
||
/avg { |
/avg { |
||
dup length |
dup length |
||
Line 2,387: | Line 3,023: | ||
} ifte |
} ifte |
||
}. |
}. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
The hard way by calculating a sum and dividing: |
The hard way by calculating a sum and dividing: |
||
< |
<syntaxhighlight lang="powershell">function mean ($x) { |
||
if ($x.Count -eq 0) { |
if ($x.Count -eq 0) { |
||
return 0 |
return 0 |
||
Line 2,401: | Line 3,037: | ||
return $sum / $x.Count |
return $sum / $x.Count |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
or, shorter, by using the <code>Measure-Object</code> cmdlet which already knows how to compute an average: |
or, shorter, by using the <code>Measure-Object</code> cmdlet which already knows how to compute an average: |
||
< |
<syntaxhighlight lang="powershell">function mean ($x) { |
||
if ($x.Count -eq 0) { |
if ($x.Count -eq 0) { |
||
return 0 |
return 0 |
||
Line 2,409: | Line 3,045: | ||
return ($x | Measure-Object -Average).Average |
return ($x | Measure-Object -Average).Average |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Processing}}== |
|||
<syntaxhighlight lang="processing">float mean(float[] arr) { |
|||
float out = 0; |
|||
for (float n : arr) { |
|||
out += n; |
|||
} |
|||
return out / arr.length; |
|||
}</syntaxhighlight> |
|||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
Line 2,415: | Line 3,060: | ||
{{works with|SWI-Prolog|6.6}} |
{{works with|SWI-Prolog|6.6}} |
||
< |
<syntaxhighlight lang="prolog"> |
||
mean(List, Mean) :- |
mean(List, Mean) :- |
||
length(List, Length), |
length(List, Length), |
||
sumlist(List, Sum), |
sumlist(List, Sum), |
||
Mean is Sum / Length. |
Mean is Sum / Length. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">Procedure.d mean(List number()) |
||
Protected sum=0 |
Protected sum=0 |
||
Line 2,431: | Line 3,076: | ||
ProcedureReturn sum / ListSize(number()) |
ProcedureReturn sum / ListSize(number()) |
||
; Depends on programm if zero check needed, returns nan on division by zero |
; Depends on programm if zero check needed, returns nan on division by zero |
||
EndProcedure</ |
EndProcedure</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
{{works with|Python|3.0}}.<br>{{works with|Python|2.6}}<br> |
{{works with|Python|3.0}}.<br>{{works with|Python|2.6}}<br> |
||
Uses [http://docs.python.org/3.3/library/math.html?highlight=fsum#math.fsum fsum] which tracks multiple partial sums to avoid losing precision |
Uses [http://docs.python.org/3.3/library/math.html?highlight=fsum#math.fsum fsum] which tracks multiple partial sums to avoid losing precision |
||
< |
<syntaxhighlight lang="python">from math import fsum |
||
def average(x): |
def average(x): |
||
return fsum(x)/float(len(x)) if x else 0 |
return fsum(x)/float(len(x)) if x else 0 |
||
print (average([0,0,3,1,4,1,5,9,0,0])) |
print (average([0,0,3,1,4,1,5,9,0,0])) |
||
print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))</ |
print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
< |
<syntaxhighlight lang="python">2.3 |
||
2.3</ |
2.3</syntaxhighlight> |
||
{{works with|Python|2.5}} |
{{works with|Python|2.5}} |
||
< |
<syntaxhighlight lang="python">def average(x): |
||
return sum(x)/float(len(x)) if x else 0 |
return sum(x)/float(len(x)) if x else 0 |
||
print (average([0,0,3,1,4,1,5,9,0,0])) |
print (average([0,0,3,1,4,1,5,9,0,0])) |
||
print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))</ |
print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
(Notice how the second call gave the wrong result) |
(Notice how the second call gave the wrong result) |
||
< |
<syntaxhighlight lang="python">2.3 |
||
1e-21</ |
1e-21</syntaxhighlight> |
||
{{works with|Python|2.4}} |
{{works with|Python|2.4}} |
||
< |
<syntaxhighlight lang="python">def avg(data): |
||
if len(data)==0: |
if len(data)==0: |
||
return 0 |
return 0 |
||
else: |
else: |
||
return sum(data)/float(len(data)) |
return sum(data)/float(len(data)) |
||
print avg([0,0,3,1,4,1,5,9,0,0])</ |
print avg([0,0,3,1,4,1,5,9,0,0])</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<lang |
<syntaxhighlight lang="python">2.3</syntaxhighlight> |
||
{{works with|Python|3.4}} |
|||
Since 3.4, Python has a [[http://docs.python.org/3/library/statistics.html statistics] library in the stdlib, which takes care of these precision overflow issues in a way that works for all standard types, not just float, even with values way too big or small to fit in a float. (For Python 2.6-2.7, there's a backport available on PyPI.) |
|||
<syntaxhighlight lang="python">>>> from statistics import mean |
|||
>>> mean([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]) |
|||
2.3 |
|||
>>> mean([10**10000, -10**10000, 3, 1, 4, 1, 5, 9, 0, 0]) |
|||
2.3 |
|||
>>> mean([10**10000, -10**10000, 3, 1, 4, 1, 5, 9, Fraction(1, 10**10000), Fraction(-1, 10**10000)]) |
|||
Fraction(23, 10) |
|||
>>> big = 10**10000 |
|||
>>> mean([Decimal(big), Decimal(-big), 3, 1, 4, 1, 5, 9, 1/Decimal(big), -1/Decimal(big)]) |
|||
Decimal('2.3')</syntaxhighlight> |
|||
=={{header|Q}}== |
|||
A built-in solution is <tt>avg</tt>. An implementation of it could be: |
|||
<syntaxhighlight lang="q">mean:{(sum x)%count x}</syntaxhighlight> |
|||
=={{header|Quackery}}== |
|||
Using the Quackery big number rational arithmetic library <code>bigrat.qky</code>. |
|||
<syntaxhighlight lang="quackery"> [ $ 'bigrat.qky' loadfile ] now! |
|||
[ [] swap times |
|||
[ 20001 random 10000 - |
|||
n->v 100 n->v v/ |
|||
join nested join ] ] is makevector ( --> [ ) |
|||
[ witheach |
|||
[ unpack |
|||
2 point$ echo$ |
|||
i 0 > if |
|||
[ say ", " ] ] ] is echodecs ( [ --> ) |
|||
[ dup size n->v rot |
|||
0 n->v rot |
|||
witheach |
|||
[ unpack v+ ] |
|||
2swap v/ ] is arithmean ( [ --> n/d ) |
|||
[ 5 makevector |
|||
say "Internal representation of a randomly generated vector" cr |
|||
say "of five rational numbers. They are distributed between" cr |
|||
say "-100.00 and +100.00 and are multiples of 0.01." |
|||
cr cr dup echo cr cr |
|||
say "Shown as decimal fractions." |
|||
cr cr dup echodecs cr cr |
|||
arithmean |
|||
say "Arithmetic mean of vector as a decimal fraction to" cr |
|||
say "5 places after the point, as a rounded proper" cr |
|||
say "fraction with the denominator not exceeding 10, and" cr |
|||
say "finally as a vulgar fraction without rounding." cr cr |
|||
2dup 5 point$ echo$ |
|||
say ", " |
|||
2dup proper 10 round improper |
|||
proper$ echo$ |
|||
say ", " |
|||
vulgar$ echo$ cr cr |
|||
say "The same, but with a vector of 9973 rational numbers," cr |
|||
say "20 decimal places and a denominator not exceeding 100." cr cr |
|||
9973 makevector arithmean |
|||
2dup 20 point$ echo$ |
|||
say ", " |
|||
2dup proper 100 round improper |
|||
proper$ echo$ |
|||
say ", " |
|||
vulgar$ echo$ cr ] is demonstrate ( --> )</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Internal representation of a randomly generated vector |
|||
of five rational numbers. They are distributed between |
|||
-100.00 and +100.00 and are multiples of 0.01. |
|||
[ [ -1999 100 ] [ 253 50 ] [ 2867 50 ] [ 3929 50 ] [ -25 2 ] ] |
|||
Shown as decimal fractions. |
|||
-19.99, 5.06, 57.34, 78.58, -12.5 |
|||
Arithmetic mean of vector as a decimal fraction to |
|||
5 places after the point, as a rounded proper |
|||
fraction with the denominator not exceeding 10, and |
|||
finally as a vulgar fraction without rounding. |
|||
21.698, 21 7/10, 10849/500 |
|||
The same, but with a vector of 9973 rational numbers, |
|||
20 decimal places and a denominator not exceeding 100. |
|||
-0.41664995487817106187, -5/12, -16621/39892</pre> |
|||
=={{header|R}}== |
=={{header|R}}== |
||
R has its <tt>mean</tt> function but it does not allow for NULL (void vectors or whatever) as argument: in this case it raises a warning and the result is NA. An implementation that does not suppress the warning could be: |
R has its <tt>mean</tt> function but it does not allow for NULL (void vectors or whatever) as argument: in this case it raises a warning and the result is NA. An implementation that does not suppress the warning could be: |
||
< |
<syntaxhighlight lang="rsplus">omean <- function(v) { |
||
m <- mean(v) |
m <- mean(v) |
||
ifelse(is.na(m), 0, m) |
ifelse(is.na(m), 0, m) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
Line 2,482: | Line 3,225: | ||
Racket's math library (available in v5.3.2 and newer) comes with a <tt>mean</tt> function that works on arbitrary sequences. |
Racket's math library (available in v5.3.2 and newer) comes with a <tt>mean</tt> function that works on arbitrary sequences. |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang racket |
#lang racket |
||
(require math) |
(require math) |
||
Line 2,489: | Line 3,232: | ||
(mean '(2 2 4 4)) ; -> 3 |
(mean '(2 2 4 4)) ; -> 3 |
||
(mean #(3 4 5 8)) ; -> 5 |
(mean #(3 4 5 8)) ; -> 5 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
|||
(formerly Perl 6) |
|||
{{works with|Rakudo|2015.10-11}} |
|||
<syntaxhighlight lang="raku" line>multi mean([]){ Failure.new('mean on empty list is not defined') }; # Failure-objects are lazy exceptions |
|||
multi mean (@a) { ([+] @a) / @a }</syntaxhighlight> |
|||
=={{header|Rapira}}== |
|||
<syntaxhighlight lang="rapira">fun mean(arr) |
|||
sum := 0 |
|||
for N from 1 to #arr do |
|||
sum := sum + arr[N] |
|||
od |
|||
return (sum / #arr) |
|||
end</syntaxhighlight> |
|||
=={{header|REBOL}}== |
=={{header|REBOL}}== |
||
< |
<syntaxhighlight lang="rebol">rebol [ |
||
Title: "Arithmetic Mean (Average)" |
Title: "Arithmetic Mean (Average)" |
||
Author: oofoe |
|||
Date: 2009-12-11 |
|||
URL: http://rosettacode.org/wiki/Average/Arithmetic_mean |
URL: http://rosettacode.org/wiki/Average/Arithmetic_mean |
||
] |
] |
||
Line 2,512: | Line 3,269: | ||
print [mold x: [3 1 4 1 5 9] "->" average x] |
print [mold x: [3 1 4 1 5 9] "->" average x] |
||
print [mold x: [1000 3 1 4 1 5 9 -1000] "->" average x] |
print [mold x: [1000 3 1 4 1 5 9 -1000] "->" average x] |
||
print [mold x: [1e20 3 1 4 1 5 9 -1e20] "->" average x]</ |
print [mold x: [1e20 3 1 4 1 5 9 -1e20] "->" average x]</syntaxhighlight> |
||
Output: |
Output: |
||
Line 2,520: | Line 3,277: | ||
[1000 3 1 4 1 5 9 -1000] -> 2.875 |
[1000 3 1 4 1 5 9 -1000] -> 2.875 |
||
[1E+20 3 1 4 1 5 9 -1E+20] -> 0.0</pre> |
[1E+20 3 1 4 1 5 9 -1E+20] -> 0.0</pre> |
||
=={{header|Red}}== |
|||
Red comes with the <code>average</code> function. |
|||
<syntaxhighlight lang="red">Red ["Arithmetic mean"] |
|||
print average [] |
|||
print average [2 3 5]</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
none |
|||
3.333333333333334 |
|||
</pre> |
|||
The source code for <code>average</code>: |
|||
<syntaxhighlight lang="red">average: func [ |
|||
"Returns the average of all values in a block" |
|||
block [block! vector! paren! hash!] |
|||
][ |
|||
if empty? block [return none] |
|||
divide sum block to float! length? block |
|||
]</syntaxhighlight> |
|||
=={{header|ReScript}}== |
|||
<syntaxhighlight lang="rescript">let arr = [3, 8, 4, 1, 5, 12] |
|||
let num = Js.Array.length(arr) |
|||
let tot = Js.Array.reduce(\"+", 0, arr) |
|||
let mean = float_of_int(tot) /. float_of_int(num) |
|||
Js.log(Js.Float.toString(mean))</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
$ bsc arithmean.res > arithmean.js |
|||
$ node arithmean.js |
|||
5.5 |
|||
</pre> |
|||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
Line 2,525: | Line 3,319: | ||
A check is made to validate if the numbers in the list are all numeric. |
A check is made to validate if the numbers in the list are all numeric. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program finds the averages/arithmetic mean of several lists (vectors) or CL input*/ |
||
parse arg @.1; if @.1='' then do; #=6 /*vector from the C.L.?*/ |
parse arg @.1; if @.1='' then do; #=6 /*vector from the C.L.?*/ |
||
@.1 = 10 9 8 7 6 5 4 3 2 1 |
@.1 = 10 9 8 7 6 5 4 3 2 1 |
||
Line 2,551: | Line 3,345: | ||
if #==0 then return 'N/A: ───[no numeric values.]' /*No nums? Return N/A*/ |
if #==0 then return 'N/A: ───[no numeric values.]' /*No nums? Return N/A*/ |
||
return $ / # /*return the average. */</ |
return $ / # /*return the average. */</syntaxhighlight> |
||
'''output''' when using the (internal) lists: |
'''output''' when using the (internal) lists: |
||
<pre> |
<pre> |
||
Line 2,586: | Line 3,380: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
nums = [1,2,3,4,5,6,7,8,9,10] |
nums = [1,2,3,4,5,6,7,8,9,10] |
||
sum = 0 |
sum = 0 |
||
Line 2,596: | Line 3,390: | ||
next |
next |
||
return sum/len(numbers) |
return sum/len(numbers) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|RPL |
=={{header|RPL}}== |
||
This is based on the dc version above. |
|||
{{works with|HP|48G}} |
|||
≪ DUP 'N' STO →LIST ΣLIST N / 'N' PURGE ≫ '<span style="color:blue">AMEAN</span>' STO |
|||
or,by using the stack instead of a temporary variable: |
|||
≪ →LIST ΣLIST LASTARG SIZE / ≫ '<span style="color:blue">AMEAN</span>' STO |
|||
CLEAR 1 2 3 5 7 DEPTH <span style="color:blue">AMEAN</span> |
|||
This is a simple rewrite of the dc version above. This works on an HP 48. "->" is a single right arrow character on the 48. Feel free to alter this code as necessary to work on RPL/2. |
|||
===Hard-working approach=== |
|||
<lang rpl/2>1 2 3 5 7 |
|||
Works for all RPL versions. |
|||
AMEAN |
|||
≪ DUP SIZE SWAP OVER |
|||
<< DEPTH DUP 'N' STO ->LIST ΣLIST N / >> |
|||
0 1 ROT '''FOR''' j |
|||
3.6</lang> |
|||
OVER j GET + '''NEXT''' |
|||
ROT / SWAP DROP |
|||
≫ |
|||
===Hard-working approach with local variables=== |
|||
No significant impact on program size or speed, but much more readable |
|||
≪ DUP SIZE → vector n |
|||
≪ 0 1 n '''FOR''' j |
|||
vector j GET + '''NEXT''' |
|||
n / |
|||
≫ ≫ |
|||
===Straightforward approach=== |
|||
The dot product of any vector with [1 1 ... 1] gives the sum of its elements. |
|||
≪ SIZE LAST DUP 1 CON DOT SWAP / ≫ |
|||
''''AMEAN'''' STO |
|||
===Using built-in statistics features=== |
|||
Most of the code is dedicated to store the input array according to built-in statistics requirements, which requires a matrix with one line per record. Main benefit of this approach is that you can then easily calculate standard deviation and variance by calling resp. <code>SDEV</code> and <code>VAR</code> functions. |
|||
≪ { 1 } OVER SIZE + RDM TRN '∑DAT' STO MEAN ≫ ''''AMEAN'''' STO |
|||
[ 1 5 0 -4 6 ] '''AMEAN''' |
|||
{{out}} |
|||
<pre> |
|||
1: 1.6 |
|||
</pre> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">def mean(nums) |
||
nums. |
nums.sum(0.0) / nums.size |
||
end |
end |
||
Line 2,616: | Line 3,439: | ||
ary = nums[0,i] |
ary = nums[0,i] |
||
puts "array size #{ary.size} : #{mean(ary)}" |
puts "array size #{ary.size} : #{mean(ary)}" |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,629: | Line 3,452: | ||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
< |
<syntaxhighlight lang="runbasic">print "Gimme the number in the array:";input numArray |
||
dim value(numArray) |
dim value(numArray) |
||
for i = 1 to numArray |
for i = 1 to numArray |
||
Line 2,639: | Line 3,462: | ||
next |
next |
||
if totValue <> 0 then mean = totValue/numArray |
if totValue <> 0 then mean = totValue/numArray |
||
print "The mean is: ";mean</ |
print "The mean is: ";mean</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust">fn sum(arr: &[f64]) -> f64 { |
||
arr.iter().fold(0.0, |p,&q| p + q) |
arr.iter().fold(0.0, |p,&q| p + q) |
||
} |
} |
||
Line 2,656: | Line 3,479: | ||
let w = &[]; |
let w = &[]; |
||
println!("mean of {:?}: {:?}", w, mean(w)); |
println!("mean of {:?}: {:?}", w, mean(w)); |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>mean of [2, 3, 5, 7, 13, 21, 33, 54]: 17.25 |
<pre>mean of [2, 3, 5, 7, 13, 21, 33, 54]: 17.25 |
||
Line 2,663: | Line 3,486: | ||
=={{header|Sather}}== |
=={{header|Sather}}== |
||
Built to work with VEC, ("geometric" vectors), whose elements must be floats. A 0-dimension vector yields "nan". |
Built to work with VEC, ("geometric" vectors), whose elements must be floats. A 0-dimension vector yields "nan". |
||
< |
<syntaxhighlight lang="sather">class VECOPS is |
||
mean(v:VEC):FLT is |
mean(v:VEC):FLT is |
||
m ::= 0.0; |
m ::= 0.0; |
||
Line 2,676: | Line 3,499: | ||
#OUT + VECOPS::mean(v) + "\n"; |
#OUT + VECOPS::mean(v) + "\n"; |
||
end; |
end; |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
Using Scala 2.7, this has to be defined for each numeric type: |
Using Scala 2.7, this has to be defined for each numeric type: |
||
< |
<syntaxhighlight lang="scala">def mean(s: Seq[Int]) = s.foldLeft(0)(_+_) / s.size</syntaxhighlight> |
||
However, Scala 2.8 gives much more flexibility, but you still have to opt |
However, Scala 2.8 gives much more flexibility, but you still have to opt |
||
between integral types and fractional types. For example: |
between integral types and fractional types. For example: |
||
< |
<syntaxhighlight lang="scala">def mean[T](s: Seq[T])(implicit n: Integral[T]) = { |
||
import n._ |
import n._ |
||
s.foldLeft(zero)(_+_) / fromInt(s.size) |
s.foldLeft(zero)(_+_) / fromInt(s.size) |
||
}</ |
}</syntaxhighlight> |
||
This can be used with any subclass of <tt>Sequence</tt> on integral types, up |
This can be used with any subclass of <tt>Sequence</tt> on integral types, up |
||
Line 2,699: | Line 3,522: | ||
Alas, Scala 2.8 also simplifies the task in another way: |
Alas, Scala 2.8 also simplifies the task in another way: |
||
< |
<syntaxhighlight lang="scala">def mean[T](s: Seq[T])(implicit n: Fractional[T]) = n.div(s.sum, n.fromInt(s.size))</syntaxhighlight> |
||
Here we show a function that supports fractional types. Instead of importing the definitions |
Here we show a function that supports fractional types. Instead of importing the definitions |
||
Line 2,707: | Line 3,530: | ||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
< |
<syntaxhighlight lang="scheme">(define (mean l) |
||
(if (null? l) |
(if (null? l) |
||
0 |
0 |
||
(/ (apply + l) (length l))))</ |
(/ (apply + l) (length l))))</syntaxhighlight> |
||
> (mean (list 3 1 4 1 5 9)) |
> (mean (list 3 1 4 1 5 9)) |
||
Line 2,716: | Line 3,539: | ||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
include "float.s7i"; |
include "float.s7i"; |
||
Line 2,739: | Line 3,562: | ||
begin |
begin |
||
writeln(mean(numVector)); |
writeln(mean(numVector)); |
||
end func;</ |
end func;</syntaxhighlight> |
||
=={{header|SenseTalk}}== |
|||
SenseTalk has a built-in average function. |
|||
<syntaxhighlight lang="sensetalk">put the average of [12,92,-17,66,128] |
|||
put average(empty) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
56.2 |
|||
nan |
|||
</pre> |
|||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">func avg(Array list) { |
||
list.len > 0 || return 0 |
list.len > 0 || return 0 |
||
list.sum / list.len |
list.sum / list.len |
||
} |
} |
||
say avg([ |
say avg([Inf, Inf]) |
||
say avg([3,1,4,1,5,9]) |
say avg([3,1,4,1,5,9]) |
||
say avg([1e+20, 3, 1, 4, 1, 5, 9, -1e+20]) |
say avg([1e+20, 3, 1, 4, 1, 5, 9, -1e+20]) |
||
say avg([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0.11]) |
say avg([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0.11]) |
||
say avg([10, 20, 30, 40, 50, -100, 4.7, -1100]) |
say avg([10, 20, 30, 40, 50, -100, 4.7, -1100])</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Inf |
|||
3.833333333333333333333333333333333333333 |
|||
3.83333333333333333333333333333333333333333333333 |
|||
2.875 |
2.875 |
||
3.674 |
3.674 |
||
-130.6625 |
-130.6625 |
||
</pre> |
|||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
< |
<syntaxhighlight lang="slate">[|:list| (list reduce: #+ `er ifEmpty: [0]) / (list isEmpty ifTrue: [1] ifFalse: [list size])] applyWith: #(3 1 4 1 5 9). |
||
[|:list| (list reduce: #+ `er ifEmpty: [0]) / (list isEmpty ifTrue: [1] ifFalse: [list size])] applyWith: {}.</ |
[|:list| (list reduce: #+ `er ifEmpty: [0]) / (list isEmpty ifTrue: [1] ifFalse: [list size])] applyWith: {}.</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
< |
<syntaxhighlight lang="smalltalk"> |
||
| numbers | |
| numbers | |
||
Line 2,774: | Line 3,611: | ||
(numbers inject: 0 into: [:sumSoFar :eachElement | sumSoFar + eachElement]) / numbers size ] |
(numbers inject: 0 into: [:sumSoFar :eachElement | sumSoFar + eachElement]) / numbers size ] |
||
) displayNl. |
) displayNl. |
||
</syntaxhighlight> |
|||
</lang> |
|||
However, the empty check can be omitted, as inject returns the injected value for empty collections, and we probably do not care for the average of nothing (i.e. the division by zero exception): |
However, the empty check can be omitted, as inject returns the injected value for empty collections, and we probably do not care for the average of nothing (i.e. the division by zero exception): |
||
< |
<syntaxhighlight lang="smalltalk"> |
||
| numbers | |
| numbers | |
||
numbers := #(1 2 3 4 5 6 7 8). |
numbers := #(1 2 3 4 5 6 7 8). |
||
( numbers inject: 0 into: [:sumSoFar :eachElement | sumSoFar + eachElement]) / numbers size] ) displayNl. |
( numbers inject: 0 into: [:sumSoFar :eachElement | sumSoFar + eachElement]) / numbers size] ) displayNl. |
||
</syntaxhighlight> |
|||
</lang> |
|||
also, most Smalltalk's collection classes already provide sum and average methods, which makes it: |
also, most Smalltalk's collection classes already provide sum and average methods, which makes it: |
||
{{works with|Pharo}} |
{{works with|Pharo}} |
||
{{works with|Smalltalk/X}} |
{{works with|Smalltalk/X}} |
||
< |
<syntaxhighlight lang="smalltalk"> |
||
| numbers | |
| numbers | |
||
numbers := #(1 2 3 4 5 6 7 8). |
numbers := #(1 2 3 4 5 6 7 8). |
||
(numbers sum / numbers size) displayNl. |
(numbers sum / numbers size) displayNl. |
||
</syntaxhighlight> |
|||
</lang> |
|||
or |
or |
||
< |
<syntaxhighlight lang="smalltalk"> |
||
| numbers | |
| numbers | |
||
numbers := #(1 2 3 4 5 6 7 8). |
numbers := #(1 2 3 4 5 6 7 8). |
||
numbers average displayNl. |
numbers average displayNl. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|SNOBOL4}}== |
=={{header|SNOBOL4}}== |
||
Line 2,805: | Line 3,642: | ||
{{works with|CSnobol}} |
{{works with|CSnobol}} |
||
< |
<syntaxhighlight lang="snobol4"> define('avg(a)i,sum') :(avg_end) |
||
avg i = i + 1; sum = sum + a<i> :s(avg) |
avg i = i + 1; sum = sum + a<i> :s(avg) |
||
avg = 1.0 * sum / prototype(a) :(return) |
avg = 1.0 * sum / prototype(a) :(return) |
||
Line 2,818: | Line 3,655: | ||
output = '[' str '] -> ' avg(arr) |
output = '[' str '] -> ' avg(arr) |
||
output = '[ ] -> ' avg(empty) |
output = '[ ] -> ' avg(empty) |
||
end</ |
end</syntaxhighlight> |
||
Output: |
Output: |
||
Line 2,826: | Line 3,663: | ||
=={{header|SQL}}== |
=={{header|SQL}}== |
||
Tested on Oracle 11gR2, the more limited the tool, the more resourceful one becomes :) |
Tested on Oracle 11gR2, the more limited the tool, the more resourceful one becomes :) |
||
<syntaxhighlight lang="sql"> |
|||
<lang SQL> |
|||
create table "numbers" ("datapoint" integer); |
create table "numbers" ("datapoint" integer); |
||
Line 2,832: | Line 3,669: | ||
select sum("datapoint")/count(*) from "numbers"; |
select sum("datapoint")/count(*) from "numbers"; |
||
</syntaxhighlight> |
|||
</lang> |
|||
...or... |
|||
<syntaxhighlight lang="sql">select avg("datapoint") from "numbers";</syntaxhighlight> |
|||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
These functions return a real: |
These functions return a real: |
||
< |
<syntaxhighlight lang="sml">fun mean_reals [] = 0.0 |
||
| mean_reals xs = foldl op+ 0.0 xs / real (length xs); |
| mean_reals xs = foldl op+ 0.0 xs / real (length xs); |
||
val mean_ints = mean_reals o (map real);</ |
val mean_ints = mean_reals o (map real);</syntaxhighlight> |
||
The previous code is easier to read and understand, though if you want |
The previous code is easier to read and understand, though if you want |
||
Line 2,849: | Line 3,689: | ||
would rather be handled by an exception. |
would rather be handled by an exception. |
||
< |
<syntaxhighlight lang="sml">fun mean_reals [] = raise Empty |
||
| mean_reals xs = let |
| mean_reals xs = let |
||
val (total, length) = |
val (total, length) = |
||
Line 2,868: | Line 3,708: | ||
in |
in |
||
(real total / length) |
(real total / length) |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|Stata}}== |
|||
=== Mean of a dataset variable === |
|||
Illustration of the mean on the population (in millions) in january 2016 of a few european countries (source [http://appsso.eurostat.ec.europa.eu/nui/show.do?dataset=demo_gind&lang=fr Eurostat]). |
|||
<syntaxhighlight lang="text">clear all |
|||
input str20 country population |
|||
Belgium 11311.1 |
|||
Bulgaria 7153.8 |
|||
"Czech Republic" 10553.8 |
|||
Denmark 5707.3 |
|||
Germany 82175.7 |
|||
Estonia 1315.9 |
|||
Ireland 4724.7 |
|||
Greece 10783.7 |
|||
end |
|||
. mean population |
|||
Mean estimation Number of obs = 8 |
|||
-------------------------------------------------------------- |
|||
| Mean Std. Err. [95% Conf. Interval] |
|||
-------------+------------------------------------------------ |
|||
population | 16715.75 9431.077 -5585.203 39016.7 |
|||
-------------------------------------------------------------- |
|||
. tabstat population, statistic(mean) |
|||
variable | mean |
|||
-------------+---------- |
|||
population | 16715.75 |
|||
------------------------ |
|||
. quietly summarize population |
|||
. display r(mean) |
|||
16715.75</syntaxhighlight> |
|||
=== Mean in Mata === |
|||
<syntaxhighlight lang="stata">mata |
|||
a=11311.1\7153.8\10553.8\5707.3\ |
|||
82175.7\1315.9\4724.7\10783.7 |
|||
mean(a) |
|||
16715.75</syntaxhighlight> |
|||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">func meanDoubles(s: [Double]) -> Double { |
||
return s.reduce(0, +) / Double(s.count) |
return s.reduce(0, +) / Double(s.count) |
||
} |
} |
||
func meanInts(s: [Int]) -> Double { |
func meanInts(s: [Int]) -> Double { |
||
return meanDoubles(s.map{Double($0)}) |
return meanDoubles(s.map{Double($0)}) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.5 |
||
proc mean args { |
proc mean args { |
||
if {[set num [llength $args]] == 0} {return 0} |
if {[set num [llength $args]] == 0} {return 0} |
||
expr {[tcl::mathop::+ {*}$args] / double($num)} |
expr {[tcl::mathop::+ {*}$args] / double($num)} |
||
} |
} |
||
mean 3 1 4 1 5 9 ;# ==> 3.8333333333333335</ |
mean 3 1 4 1 5 9 ;# ==> 3.8333333333333335</syntaxhighlight> |
||
=={{header|TI-83 BASIC}}== |
=={{header|TI-83 BASIC}}== |
||
<lang |
<syntaxhighlight lang="ti83b">Mean(Ans</syntaxhighlight> |
||
=={{header|TI-89 BASIC}}== |
=={{header|TI-89 BASIC}}== |
||
< |
<syntaxhighlight lang="ti89b">Define rcmean(nums) = when(dim(nums) = 0, 0, mean(nums))</syntaxhighlight> |
||
=={{header|Trith}}== |
=={{header|Trith}}== |
||
< |
<syntaxhighlight lang="trith">: mean dup empty? [drop 0] [dup [+] foldl1 swap length /] branch ; |
||
[3 1 4 1 5 9] mean</ |
[3 1 4 1 5 9] mean</syntaxhighlight> |
||
=={{header|TypeScript}}== |
=={{header|TypeScript}}== |
||
< |
<syntaxhighlight lang="typescript"> |
||
function mean(numbersArr) |
function mean(numbersArr) |
||
{ |
{ |
||
Line 2,915: | Line 3,798: | ||
alert( mean( [1,2,3,4,5] ) ); |
alert( mean( [1,2,3,4,5] ) ); |
||
alert( mean( [] ) ); |
alert( mean( [] ) ); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header| |
=={{header|UNIX Shell}}== |
||
1) First solution with bash (V >= 3), works with floats : |
|||
{{incorrect|UnixPipes|There is a race between parallel commands. <code>cat count</code> might try to read the file before <code>wc -l >count</code> writes it. This may cause an error like ''cat: count: No such file or directory'', then ''bc: stdin:1: syntax error: ) unexpected''.}} |
|||
<syntaxhighlight lang="bash1">echo "`cat f | paste -sd+ | bc -l` / `cat f | wc -l`" | bc -l |
|||
</syntaxhighlight> |
|||
<syntaxhighlight lang="bash1">cat f |
|||
1 |
|||
2 |
|||
4 |
|||
8 |
|||
16 |
|||
-200 |
|||
echo "`cat f | paste -sd+ | bc -l`/`cat f | wc -l`" | bc -l |
|||
Uses [[ksh93]]-style process substitution. Also overwrites the file named <tt>count</tt> in the current directory. |
|||
-28.16666666666666666666 |
|||
{{works with|bash}} |
|||
<lang bash>term() { |
|||
b=$1;res=$2 |
|||
echo "scale=5;$res+$b" | bc |
|||
} |
|||
cat f |
|||
sum() { |
|||
1.109434 |
|||
(read B; res=$1; |
|||
2 |
|||
test -n "$B" && (term $B $res) || (term 0 $res)) |
|||
4.5 |
|||
} |
|||
8.45 |
|||
16 |
|||
-200 |
|||
400.56 |
|||
echo "`cat f | paste -sd+ | bc -l`/`cat f | wc -l`" |bc -l |
|||
fold() { |
|||
33.23134771428571428571 |
|||
func=$1 |
|||
</syntaxhighlight> |
|||
(while read a ; do |
|||
fold $func | $func $a |
|||
done) |
|||
} |
|||
2) This example uses <tt>expr</tt>, so it only works with integers. It checks that each string in the list is an integer. |
|||
mean() { |
|||
tee >(wc -l > count) | fold sum | xargs echo "scale=5;(1/" $(cat count) ") * " | bc |
|||
} |
|||
(echo 3; echo 1; echo 4) | mean</lang> |
|||
=={{header|UNIX Shell}}== |
|||
This example uses <tt>expr</tt>, so it only works with integers. It checks that each string in the list is an integer. |
|||
< |
<syntaxhighlight lang="bash">mean() { |
||
if expr $# >/dev/null; then |
if expr $# >/dev/null; then |
||
(count=0 |
(count=0 |
||
Line 2,971: | Line 3,853: | ||
printf "test 4: "; mean -400 400 -1300 200 # -275 |
printf "test 4: "; mean -400 400 -1300 200 # -275 |
||
printf "test 5: "; mean - # expr: syntax error |
printf "test 5: "; mean - # expr: syntax error |
||
printf "test 6: "; mean 1 2 A 3 # expr: non-numeric argument</ |
printf "test 6: "; mean 1 2 A 3 # expr: non-numeric argument</syntaxhighlight> |
||
=={{header|UnixPipes}}== |
|||
{{incorrect|UnixPipes|There is a race between parallel commands. <code>cat count</code> might try to read the file before <code>wc -l >count</code> writes it. This may cause an error like ''cat: count: No such file or directory'', then ''bc: stdin:1: syntax error: ) unexpected''.}} |
|||
Uses [[ksh93]]-style process substitution. Also overwrites the file named <tt>count</tt> in the current directory. |
|||
{{works with|bash}} |
|||
<syntaxhighlight lang="bash">term() { |
|||
b=$1;res=$2 |
|||
echo "scale=5;$res+$b" | bc |
|||
} |
|||
sum() { |
|||
(read B; res=$1; |
|||
test -n "$B" && (term $B $res) || (term 0 $res)) |
|||
} |
|||
fold() { |
|||
func=$1 |
|||
(while read a ; do |
|||
fold $func | $func $a |
|||
done) |
|||
} |
|||
mean() { |
|||
tee >(wc -l > count) | fold sum | xargs echo "scale=5;(1/" $(cat count) ") * " | bc |
|||
} |
|||
(echo 3; echo 1; echo 4) | mean</syntaxhighlight> |
|||
=={{header|Ursa}}== |
=={{header|Ursa}}== |
||
< |
<syntaxhighlight lang="ursa"># |
||
# arithmetic mean |
# arithmetic mean |
||
# |
# |
||
Line 2,984: | Line 3,894: | ||
end for |
end for |
||
out (/ (+ input) (size input)) endl console</ |
out (/ (+ input) (size input)) endl console</syntaxhighlight> |
||
=={{header|Ursala}}== |
=={{header|Ursala}}== |
||
There is a library function for means already, although it doesn't cope with |
There is a library function for means already, although it doesn't cope with |
||
empty vectors. A mean function could be defined as shown for this task. |
empty vectors. A mean function could be defined as shown for this task. |
||
< |
<syntaxhighlight lang="ursala">#import nat |
||
#import flo |
#import flo |
||
Line 2,996: | Line 3,906: | ||
#cast %e |
#cast %e |
||
example = mean <5.,3.,-2.,6.,-4.></ |
example = mean <5.,3.,-2.,6.,-4.></syntaxhighlight> |
||
output: |
output: |
||
<pre>1.600000e+00</pre> |
<pre>1.600000e+00</pre> |
||
=={{header|V}}== |
=={{header|V}}== |
||
< |
<syntaxhighlight lang="v">[mean |
||
[sum 0 [+] fold]. |
[sum 0 [+] fold]. |
||
dup sum |
dup sum |
||
swap size [[1 <] [1]] when / |
swap size [[1 <] [1]] when / |
||
].</ |
].</syntaxhighlight> |
||
=={{header|Vala}}== |
=={{header|Vala}}== |
||
Using array to hold the numbers of the list: |
Using array to hold the numbers of the list: |
||
< |
<syntaxhighlight lang="vala"> |
||
double arithmetic(double[] list){ |
double arithmetic(double[] list){ |
||
double mean; |
double mean; |
||
Line 3,036: | Line 3,945: | ||
stdout.printf("%s\n", mean_zero.to_string()); |
stdout.printf("%s\n", mean_zero.to_string()); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
Line 3,043: | Line 3,952: | ||
0 |
0 |
||
</pre> |
</pre> |
||
=={{header|VBA}}== |
|||
<syntaxhighlight lang="vb">Private Function mean(v() As Double, ByVal leng As Integer) As Variant |
|||
Dim sum As Double, i As Integer |
|||
sum = 0: i = 0 |
|||
For i = 0 To leng - 1 |
|||
sum = sum + vv |
|||
Next i |
|||
If leng = 0 Then |
|||
mean = CVErr(xlErrDiv0) |
|||
Else |
|||
mean = sum / leng |
|||
End If |
|||
End Function |
|||
Public Sub main() |
|||
Dim v(4) As Double |
|||
Dim i As Integer, leng As Integer |
|||
v(0) = 1# |
|||
v(1) = 2# |
|||
v(2) = 2.178 |
|||
v(3) = 3# |
|||
v(4) = 3.142 |
|||
For leng = 5 To 0 Step -1 |
|||
Debug.Print "mean["; |
|||
For i = 0 To leng - 1 |
|||
Debug.Print IIf(i, "; " & v(i), "" & v(i)); |
|||
Next i |
|||
Debug.Print "] = "; mean(v, leng) |
|||
Next leng |
|||
End Sub</syntaxhighlight>{{out}} |
|||
<pre>mean[1; 2; 2,178; 3; 3,142] = 0 |
|||
mean[1; 2; 2,178; 3] = 0 |
|||
mean[1; 2; 2,178] = 0 |
|||
mean[1; 2] = 0 |
|||
mean[1] = 0 |
|||
mean[] = Fout 2007</pre> |
|||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
Function mean(arr) |
Function mean(arr) |
||
size = UBound(arr) + 1 |
size = UBound(arr) + 1 |
||
Line 3,057: | Line 4,002: | ||
'Example |
'Example |
||
WScript.Echo mean(Array(3,1,4,1,5,9)) |
WScript.Echo mean(Array(3,1,4,1,5,9)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
Line 3,064: | Line 4,009: | ||
=={{header|Vedit macro language}}== |
=={{header|Vedit macro language}}== |
||
The numeric data is stored in current edit buffer as ASCII strings, one value per line. |
The numeric data is stored in current edit buffer as ASCII strings, one value per line. |
||
< |
<syntaxhighlight lang="vedit">#1 = 0 // Sum |
||
#2 = 0 // Count |
#2 = 0 // Count |
||
BOF |
BOF |
||
Line 3,073: | Line 4,018: | ||
} |
} |
||
if (#2) { #1 /= #2 } |
if (#2) { #1 /= #2 } |
||
Num_Type(#1)</ |
Num_Type(#1)</syntaxhighlight> |
||
=={{header|Vim Script}}== |
=={{header|Vim Script}}== |
||
Throws an exception if the list is empty. |
Throws an exception if the list is empty. |
||
< |
<syntaxhighlight lang="vim">function Mean(lst) |
||
if empty(a:lst) |
if empty(a:lst) |
||
throw "Empty" |
throw "Empty" |
||
Line 3,086: | Line 4,031: | ||
endfor |
endfor |
||
return sum / len(a:lst) |
return sum / len(a:lst) |
||
endfunction</ |
endfunction</syntaxhighlight> |
||
=={{header|V (Vlang)}}== |
|||
<syntaxhighlight lang="v (vlang)">import math |
|||
import arrays |
|||
fn main() { |
|||
for v in [ |
|||
[]f64{}, // mean returns ok = false |
|||
[math.inf(1), math.inf(1)], // answer is +Inf |
|||
// answer is NaN, and mean returns ok = true, indicating NaN |
|||
// is the correct result |
|||
[math.inf(1), math.inf(-1)], |
|||
[f64(3), 1, 4, 1, 5, 9], |
|||
[f64(10), 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11], |
|||
[f64(10), 20, 30, 40, 50, -100, 4.7, -11e2], |
|||
] { |
|||
println("Vector: $v") |
|||
m := arrays.fold(v, 0.0, fn(r f64, v f64) f64 { return r+v })/v.len |
|||
println("Mean of $v.len numbers is $m\n") |
|||
} |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Vector: [] |
|||
Mean of 0 numbers is nan |
|||
Vector: [+inf, +inf] |
|||
Mean of 2 numbers is +inf |
|||
Vector: [+inf, -inf] |
|||
Mean of 2 numbers is nan |
|||
Vector: [3, 1, 4, 1, 5, 9] |
|||
Mean of 6 numbers is 3.8333333333333335 |
|||
Vector: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0.11] |
|||
Mean of 15 numbers is 3.674 |
|||
Vector: [10, 20, 30, 40, 50, -100, 4.7, -1100] |
|||
Mean of 8 numbers is -130.66</pre> |
|||
=={{header|Wart}}== |
=={{header|Wart}}== |
||
< |
<syntaxhighlight lang="python">def (mean l) |
||
sum.l / len.l</ |
sum.l / len.l</syntaxhighlight> |
||
Example run: |
Example run: |
||
Line 3,096: | Line 4,083: | ||
=> 2</pre> |
=> 2</pre> |
||
=={{header| |
=={{header|WDTE}}== |
||
<syntaxhighlight lang="wdte">let s => import 'stream'; |
|||
<lang wren>class Arithmetic { |
|||
let a => import 'arrays'; |
|||
static mean(arr) { |
|||
if (arr.count == 0) Fiber.abort("Length must be greater than zero") |
|||
let mean nums => |
|||
return arr.reduce(Fn.new{ |x,y| x+y }) / arr.count |
|||
a.stream nums |
|||
} |
|||
-> s.reduce [0; 0] (@ s p n => [+ (a.at p 0) 1; + (a.at p 1) n]) |
|||
} |
|||
-> (@ s p => / (a.at p 1) (a.at p 0));</syntaxhighlight> |
|||
Arithmetic.mean([1,2,3,4,5]) // 3 |
|||
</lang> |
|||
This is a tad messier than it has to be due to a lack of a way to get the length of an array in WDTE currently. |
|||
Usage: |
|||
<syntaxhighlight lang="wdte">mean [1; 2; 3] -- io.writeln io.stdout;</syntaxhighlight> |
|||
Output: |
|||
<pre>2</pre> |
|||
=={{header|Wortel}}== |
=={{header|Wortel}}== |
||
< |
<syntaxhighlight lang="wortel">@let { |
||
; using a fork (sum divided-by length) |
; using a fork (sum divided-by length) |
||
mean1 @(@sum / #) |
mean1 @(@sum / #) |
||
Line 3,118: | Line 4,112: | ||
!mean2 [3 1 4 1 5 9 2] |
!mean2 [3 1 4 1 5 9 2] |
||
]] |
]] |
||
}</ |
}</syntaxhighlight> |
||
Returns: |
Returns: |
||
<pre>[3.5714285714285716 3.5714285714285716]</pre> |
<pre>[3.5714285714285716 3.5714285714285716]</pre> |
||
=={{header|Wren}}== |
|||
<syntaxhighlight lang="wren">class Arithmetic { |
|||
static mean(arr) { |
|||
if (arr.count == 0) Fiber.abort("Length must be greater than zero") |
|||
return arr.reduce(Fn.new{ |x,y| x+y }) / arr.count |
|||
} |
|||
} |
|||
Arithmetic.mean([1,2,3,4,5]) // 3</syntaxhighlight> |
|||
=={{header|XLISP}}== |
=={{header|XLISP}}== |
||
The specification calls for a function that takes a vector; for convenience, we convert this vector internally to a list. The mean of a zero-length vector is returned as <tt>nil</tt>, equivalent to the empty list or logical <tt>false</tt>. |
The specification calls for a function that takes a vector; for convenience, we convert this vector internally to a list. The mean of a zero-length vector is returned as <tt>nil</tt>, equivalent to the empty list or logical <tt>false</tt>. |
||
< |
<syntaxhighlight lang="lisp">(defun mean (v) |
||
(if (= (vector-length v) 0) |
(if (= (vector-length v) 0) |
||
nil |
nil |
||
(let ((l (vector->list v))) |
(let ((l (vector->list v))) |
||
(/ (apply + l) (length l)))))</ |
(/ (apply + l) (length l)))))</syntaxhighlight> |
||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">code CrLf=9; |
||
code real RlOut=48; |
code real RlOut=48; |
||
Line 3,147: | Line 4,150: | ||
[Test:= [1.0, 2.0, 5.0, -5.0, 9.5, 3.14159]; |
[Test:= [1.0, 2.0, 5.0, -5.0, 9.5, 3.14159]; |
||
RlOut(0, Mean(Test, 6)); CrLf(0); |
RlOut(0, Mean(Test, 6)); CrLf(0); |
||
]</ |
]</syntaxhighlight> |
||
Output: |
Output: |
||
Line 3,158: | Line 4,161: | ||
Where <code>$values</code> is some variable indicating a set of nodes containing numbers, the average is given by the XPath expression: |
Where <code>$values</code> is some variable indicating a set of nodes containing numbers, the average is given by the XPath expression: |
||
< |
<syntaxhighlight lang="xpath">sum($values) div count($values)</syntaxhighlight> |
||
===Runnable example=== |
===Runnable example=== |
||
< |
<syntaxhighlight lang="xml"><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> |
||
<xsl:output method="text"/> |
<xsl:output method="text"/> |
||
Line 3,169: | Line 4,172: | ||
<xsl:value-of select="sum($values) div count($values)"/> |
<xsl:value-of select="sum($values) div count($values)"/> |
||
</xsl:template> |
</xsl:template> |
||
</xsl:stylesheet></ |
</xsl:stylesheet></syntaxhighlight> |
||
Sample input: |
Sample input: |
||
< |
<syntaxhighlight lang="xml"><numbers> |
||
<!-- Average is 2.4 --> |
<!-- Average is 2.4 --> |
||
<number>1</number> |
<number>1</number> |
||
Line 3,180: | Line 4,183: | ||
<number>3</number> |
<number>3</number> |
||
<number>5</number> |
<number>5</number> |
||
</numbers></ |
</numbers></syntaxhighlight> |
||
=={{header|Yorick}}== |
=={{header|Yorick}}== |
||
< |
<syntaxhighlight lang="yorick">func mean(x) { |
||
if(is_void(x)) return 0; |
if(is_void(x)) return 0; |
||
return x(*)(avg); |
return x(*)(avg); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
Converts int to floats (implicitly): |
Converts int to floats (implicitly): |
||
< |
<syntaxhighlight lang="zkl">fcn mean(a,b,c,etc){ z:=vm.arglist; z.reduce('+,0.0)/z.len() } |
||
mean(3,1,4,1,5,9); //-->3.83333 |
mean(3,1,4,1,5,9); //-->3.83333 |
||
mean(); //-->Exception thrown: MathError(NaN (Not a number))</ |
mean(); //-->Exception thrown: MathError(NaN (Not a number))</syntaxhighlight> |
||
To pass in a vector/list: |
To pass in a vector/list: |
||
< |
<syntaxhighlight lang="zkl">fcn meanV(z){ z.reduce('+,0.0)/z.len() } |
||
meanV(T(3,1,4,1,5,9)); // --> 3.83333</ |
meanV(T(3,1,4,1,5,9)); // --> 3.83333</syntaxhighlight> |
||
=={{header|Zoea}}== |
|||
<syntaxhighlight lang="zoea"> |
|||
program: average |
|||
case: 1 |
|||
input: [2,3,10] |
|||
output: 5 |
|||
case: 2 |
|||
input: [7,11] |
|||
output: 9 |
|||
</syntaxhighlight> |
|||
=={{header|zonnon}}== |
|||
<syntaxhighlight lang="zonnon"> |
|||
module Averages; |
|||
type |
|||
Vector = array {math} * of real; |
|||
procedure ArithmeticMean(x: Vector): real; |
|||
begin |
|||
(* sum is a predefined function for mathematical arrays *) |
|||
return sum(x) |
|||
end ArithmeticMean; |
|||
var |
|||
x: Vector; |
|||
begin |
|||
x := new Vector(4); |
|||
x := [1.0, 2.3, 3.2, 2.1, 5.3]; |
|||
write("arithmetic mean: ");writeln(ArithmeticMean(x):10:2) |
|||
end Averages. |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
arithmetic mean: 13,9 |
|||
</pre> |
Latest revision as of 11:59, 13 June 2024
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
|
0815
{x{+=<:2:x/%<:d:~$<:01:~><:02:~><:03:~><:04:~><:05:~><:06:~><:07:~><:08:
~><:09:~><:0a:~><:0b:~><:0c:~><:0d:~><:0e:~><:0f:~><:10:~><:11:~><:12:~>
<:13:~><:14:~><:15:~><:16:~><:17:~><:18:~><:19:~><:ffffffffffffffff:~>{x
{+>}:8f:{&={+>{~>&=x<:ffffffffffffffff:/#:8f:{{=<:19:x/%
- Output:
0 D
11l
F average(x)
R sum(x) / Float(x.len)
print(average([0, 0, 3, 1, 4, 1, 5, 9, 0, 0]))
- Output:
2.3
360 Assembly
Compact and functional.
AVGP CSECT
USING AVGP,12
LR 12,15
SR 3,3 i=0
SR 6,6 sum=0
LOOP CH 3,=AL2(NN-T-1) for i=1 to nn
BH ENDLOOP
L 2,T(3) t(i)
MH 2,=H'100' scaling factor=2
AR 6,2 sum=sum+t(i)
LA 3,4(3) next i
B LOOP
ENDLOOP LR 5,6 sum
LA 4,0
D 4,NN sum/nn
XDECO 5,Z edit binary
MVC U,Z+10 descale
MVI Z+10,C'.'
MVC Z+11(2),U
XPRNT Z,80 output
XR 15,15
BR 14
T DC F'10',F'9',F'8',F'7',F'6',F'5',F'4',F'3',F'2',F'1'
NN DC A((NN-T)/4)
Z DC CL80' '
U DS CL2
END AVGP
- Output:
5.50
6502 Assembly
Called as a subroutine (i.e., JSR ArithmeticMean), this calculates the integer average of up to 255 8-bit unsigned integers. The address of the beginning of the list of integers is in the memory location ArrayPtr and the number of integers is in the memory location NumberInts. The arithmetic mean is returned in the memory location ArithMean.
ArithmeticMean: PHA
TYA
PHA ;push accumulator and Y register onto stack
LDA #0
STA Temp
STA Temp+1 ;temporary 16-bit storage for total
LDY NumberInts
BEQ Done ;if NumberInts = 0 then return an average of zero
DEY ;start with NumberInts-1
AddLoop: LDA (ArrayPtr),Y
CLC
ADC Temp
STA Temp
LDA Temp+1
ADC #0
STA Temp+1
DEY
CPY #255
BNE AddLoop
LDY #-1
DivideLoop: LDA Temp
SEC
SBC NumberInts
STA Temp
LDA Temp+1
SBC #0
STA Temp+1
INY
BCS DivideLoop
Done: STY ArithMean ;store result here
PLA ;restore accumulator and Y register from stack
TAY
PLA
RTS ;return from routine
8th
: avg \ a -- avg(a)
dup ' n:+ 0 a:reduce
swap a:len nip n:/ ;
\ test:
[ 1.0, 2.3, 1.1, 5.0, 3, 2.8, 2.01, 3.14159 ] avg . cr
[ ] avg . cr
[ 10 ] avg . cr
bye
Output is:
2.54395
NaN
10.00000
ACL2
(defun mean-r (xs)
(if (endp xs)
(mv 0 0)
(mv-let (m j)
(mean-r (rest xs))
(mv (+ (first xs) m) (+ j 1)))))
(defun mean (xs)
(if (endp xs)
0
(mv-let (n d)
(mean-r xs)
(/ n d))))
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
PROC Mean(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 Test(INT ARRAY a INT count)
INT i
REAL result
Mean(a,count,result)
Print("mean(")
FOR i=0 TO count-1
DO
PrintI(a(i))
IF i<count-1 THEN
Put(',)
FI
OD
Print(")=")
PrintRE(result)
RETURN
PROC Main()
INT ARRAY a1=[1 2 3 4 5 6]
INT ARRAY a2=[1 10 100 1000 10000]
INT ARRAY a3=[9]
Put(125) PutE() ;clear screen
Test(a1,6)
Test(a2,5)
Test(a3,1)
Test(a3,0)
RETURN
- Output:
Screenshot from Atari 8-bit computer
mean(1,2,3,4,5,6)=3.5 mean(1,10,100,1000,10000)=2222.2 mean(9)=9 mean()=0
ActionScript
function mean(vector:Vector.<Number>):Number
{
var sum:Number = 0;
for(var i:uint = 0; i < vector.length; i++)
sum += vector[i];
return vector.length == 0 ? 0 : sum / vector.length;
}
Ada
This example shows how to pass a zero length vector as well as a larger vector. With Ada 2012 it is possible to check that pre conditions are satisfied (otherwise an exception is thrown). So we check that the length is not zero.
with Ada.Float_Text_Io; use Ada.Float_Text_Io;
with Ada.Text_IO; use Ada.Text_IO;
procedure Mean_Main is
type Vector is array (Positive range <>) of Float;
function Mean (Item : Vector) return float with pre => Item'length > 0;
function Mean (Item : Vector) return Float is
Sum : Float := 0.0;
begin
for I in Item'range loop
Sum := Sum + Item(I);
end loop;
return Sum / Float(Item'Length);
end Mean;
A : Vector := (3.0, 1.0, 4.0, 1.0, 5.0, 9.0);
begin
Put(Item => Mean (A), Fore => 1, Exp => 0);
New_Line;
-- test for zero length vector
Put(Item => Mean(A (1..0)), Fore => 1, Exp => 0);
New_Line;
end Mean_Main;
Output: 3.83333
raised SYSTEM.ASSERTIONS.ASSERT_FAILURE : failed precondition from mean_main.adb:6
Aime
real
mean(list l)
{
real sum, x;
sum = 0;
for (, x in l) {
sum += x;
}
sum / ~l;
}
integer
main(void)
{
o_form("%f\n", mean(list(4.5, 7.25, 5r, 5.75)));
0;
}
ALGOL 68
PROC mean = (REF[]REAL p)REAL:
# Calculates the mean of qty REALs beginning at p. #
IF LWB p > UPB p THEN 0.0
ELSE
REAL total := 0.0;
FOR i FROM LWB p TO UPB p DO total +:= p[i] OD;
total / (UPB p - LWB p + 1)
FI;
main:(
[6]REAL test := (1.0, 2.0, 5.0, -5.0, 9.5, 3.14159);
print((mean(test),new line))
)
ALGOL W
begin
% procedure to find the mean of the elements of a vector. %
% As the procedure can't find the bounds of the array for itself, %
% we pass them in lb and ub %
real procedure mean ( real array vector ( * )
; integer value lb
; integer value ub
) ;
begin
real sum;
assert( ub > lb ); % terminate the program if there are no elements %
sum := 0;
for i := lb until ub do sum := sum + vector( i );
sum / ( ( ub + 1 ) - lb )
end mean ;
% test the mean procedure by finding the mean of 1.1, 2.2, 3.3, 4.4, 5.5 %
real array numbers ( 1 :: 5 );
for i := 1 until 5 do numbers( i ) := i + ( i / 10 );
r_format := "A"; r_w := 10; r_d := 2; % set fixed point output %
write( mean( numbers, 1, 5 ) );
end.
AmigaE
Because of the way Amiga E handles floating point numbers, the passed list/vector must contain all explicitly floating point values (e.g., you need to write "1.0", not "1")
PROC mean(l:PTR TO LONG)
DEF m, i, ll
ll := ListLen(l)
IF ll = 0 THEN RETURN 0.0
m := 0.0
FOR i := 0 TO ll-1 DO m := !m + l[i]
m := !m / (ll!)
ENDPROC m
PROC main()
DEF s[20] : STRING
WriteF('mean \s\n',
RealF(s,mean([1.0, 2.0, 3.0, 4.0, 5.0]), 2))
ENDPROC
AntLang
AntLang has a built-in avg function.
avg[list]
APL
X←3 1 4 1 5 9
(+/X)÷⍴X
3.833333333
A proper function definition:
Avg←{(+⌿⍵)÷≢⍵}
Avg 1 2 3 4 5 6
3.5
Using tacit programming:
Avg← +⌿÷≢
Avg 1 2 3 4 5 6
3.5
N.B.: the symbol for Tally (≢) doesn't display correctly on Chrome-based browsers at the moment.
AppleScript
Vanilla
With vanilla AppleScript, the process is the literal one of adding the numbers and dividing by the list length. It naturally returns results of class real, but it would be simple to return integer-representable results as integers if required.
on average(listOfNumbers)
set len to (count listOfNumbers)
if (len is 0) then return missing value
set sum to 0
repeat with thisNumber in listOfNumbers
set sum to sum + thisNumber
end repeat
return sum / len
end average
average({2500, 2700, 2400, 2300, 2550, 2650, 2750, 2450, 2600, 2400})
- Output:
2530.0
ASObjC
The vanilla method above is the more efficient with lists of up to around 100 numbers. But for longer lists, using Foundation methods with AppleScriptObjectC can be useful
use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
on average(listOfNumbers)
if ((count listOfNumbers) is 0) then return missing value
set arrayOfNumbers to current application's class "NSArray"'s arrayWithArray:(listOfNumbers)
return (arrayOfNumbers's valueForKeyPath:("@avg.self")) as real
end average
average({2500, 2700, 2400, 2300, 2550, 2650, 2750, 2450, 2600, 2400})
- Output:
2530.0
Applesoft BASIC
REM COLLECTION IN DATA STATEMENTS, EMPTY DATA IS THE END OF THE COLLECTION
0 READ V$
1 IF LEN(V$) = 0 THEN END
2 N = 0
3 S = 0
4 FOR I = 0 TO 1 STEP 0
5 S = S + VAL(V$)
6 N = N + 1
7 READ V$
8 IF LEN(V$) THEN NEXT
9 PRINT S / N
10000 DATA1,2,2.718,3,3.142
63999 DATA
REM COLLECTION IN AN ARRAY, ITEM 0 IS THE SIZE OF THE COLLECTION
A(0) = 5 : A(1) = 1 : A(2) = 2 : A(3) = 2.718 : A(4) = 3 : A(5) = 3.142
N = A(0) : IF N THEN S = 0 : FOR I = 1 TO N : S = S + A(I) : NEXT : ? S / N
Arturo
arr: [1 2 3 4 5 6 7]
print average arr
- Output:
4.0
Astro
mean([1, 2, 3])
mean(1..10)
mean([])
AutoHotkey
i = 10
Loop, % i {
Random, v, -3.141592, 3.141592
list .= v "`n"
sum += v
}
MsgBox, % i ? list "`nmean: " sum/i:0
AWK
cat mean.awk
#!/usr/local/bin/gawk -f
# User defined function
function mean(v, i,n,sum) {
for (i in v) {
n++
sum += v[i]
}
if (n>0) {
return(sum/n)
} else {
return("zero-length input !")
}
}
BEGIN {
# fill a vector with random numbers
for(i=0; i < 10; i++) {
vett[i] = rand()*10
}
print mean(vett)
print mean(nothing)
}
- Output:
$ awk -f mean.awk 3.92689 zero-length input !
Babel
(3 24 18 427 483 49 14 4294 2 41) dup len <- sum ! -> / itod <<
- Output:
535
BASIC
Assume the numbers are in an array named "nums".
mean = 0
sum = 0;
FOR i = LBOUND(nums) TO UBOUND(nums)
sum = sum + nums(i);
NEXT i
size = UBOUND(nums) - LBOUND(nums) + 1
PRINT "The mean is: ";
IF size <> 0 THEN
PRINT (sum / size)
ELSE
PRINT 0
END IF
BBC BASIC
To calculate the mean of an array:
REM specific functions for the array/vector types
REM Byte Array
DEF FN_Mean_Arithmetic&(n&())
= SUM(n&()) / (DIM(n&(),1)+1)
REM Integer Array
DEF FN_Mean_Arithmetic%(n%())
= SUM(n%()) / (DIM(n%(),1)+1)
REM Float 40 array
DEF FN_Mean_Arithmetic(n())
= SUM(n()) / (DIM(n(),1)+1)
REM A String array
DEF FN_Mean_Arithmetic$(n$())
LOCAL I%, S%, sum, Q%
S% = DIM(n$(),1)
FOR I% = 0 TO S%
Q% = TRUE
ON ERROR LOCAL Q% = FALSE
IF Q% sum += EVAL(n$(I%))
NEXT
= sum / (S%+1)
REM Float 64 array
DEF FN_Mean_Arithmetic#(n#())
= SUM(n#()) / (DIM(n#(),1)+1)
Michael Hutton 14:02, 29 May 2011 (UTC)
IS-BASIC
100 NUMERIC ARR(3 TO 8)
110 LET ARR(3)=3:LET ARR(4)=1:LET ARR(5)=4:LET ARR(6)=1:LET ARR(7)=5:LET ARR(8)=9
120 PRINT AM(ARR)
130 DEF AM(REF A)
140 LET T=0
150 FOR I=LBOUND(A) TO UBOUND(A)
160 LET T=T+A(I)
170 NEXT
180 LET AM=T/SIZE(A)
190 END DEF
bc
Uses the current scale for calculating the mean.
define m(a[], n) {
auto i, s
for (i = 0; i < n; i++) {
s += a[i]
}
return(s / n)
}
Befunge
The first input is the length of the vector. If a length of 0 is entered, the result is equal to 0/0
.
&:0\:!v!:-1<
@./\$_\&+\^
blz
:mean(vec)
vec.fold_left(0, (x, y -> x + y)) / vec.length()
end
Bracmat
Here are two solutions. The first uses a while loop, the second scans the input by backtracking.
(mean1=
sum length n
. 0:?sum:?length
& whl
' ( !arg:%?n ?arg
& 1+!length:?length
& !n+!sum:?sum
)
& !sum*!length^-1
);
(mean2=
sum length n
. 0:?sum:?length
& !arg
: ?
( #%@?n
& 1+!length:?length
& !n+!sum:?sum
& ~
)
?
| !sum*!length^-1
);
To test with a list of all numbers 1 .. 999999:
( :?test
& 1000000:?Length
& whl'(!Length+-1:?Length:>0&!Length !test:?test)
& out$mean1$!test
& out$mean2$!test
)
Brat
mean = { list |
true? list.empty?, 0, { list.reduce(0, :+) / list.length }
}
p mean 1.to 10 #Prints 5.5
Burlesque
blsq ) {1 2 2.718 3 3.142}av
2.372
blsq ) {}av
NaN
BQN
Defines a tacit Avg function which works on any simple numeric list.
Avg ← +´÷≠
Avg 1‿2‿3‿4
2.5
C
Compute mean of a double
array of given length. If length is zero, does whatever 0.0/0
does (usually means returning NaN
).
#include <stdio.h>
double mean(double *v, int len)
{
double sum = 0;
int i;
for (i = 0; i < len; i++)
sum += v[i];
return sum / len;
}
int main(void)
{
double v[] = {1, 2, 2.718, 3, 3.142};
int i, len;
for (len = 5; len >= 0; len--) {
printf("mean[");
for (i = 0; i < len; i++)
printf(i ? ", %g" : "%g", v[i]);
printf("] = %g\n", mean(v, len));
}
return 0;
}
- Output:
mean[1, 2, 2.718, 3, 3.142] = 2.372 mean[1, 2, 2.718, 3] = 2.1795 mean[1, 2, 2.718] = 1.906 mean[1, 2] = 1.5 mean[1] = 1 mean[] = -nan
C#
using System;
using System.Linq;
class Program
{
static void Main()
{
Console.WriteLine(new[] { 1, 2, 3 }.Average());
}
}
Alternative version (not using the built-in function):
using System;
class Program
{
static void Main(string[] args)
{
double average = 0;
double[] numArray = { 1, 2, 3, 4, 5 };
average = Average(numArray);
Console.WriteLine(average); // Output is 3
// Alternative use
average = Average(1, 2, 3, 4, 5);
Console.WriteLine(average); // Output is still 3
Console.ReadLine();
}
static double Average(params double[] nums)
{
double d = 0;
foreach (double num in nums)
d += num;
return d / nums.Length;
}
}
C++
#include <vector>
double mean(const std::vector<double>& numbers)
{
if (numbers.size() == 0)
return 0;
double sum = 0;
for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++)
sum += *i;
return sum / numbers.size();
}
Shorter (and more idiomatic) version:
#include <vector>
#include <algorithm>
double mean(const std::vector<double>& numbers)
{
if (numbers.empty())
return 0;
return std::accumulate(numbers.begin(), numbers.end(), 0.0) / numbers.size();
}
Idiomatic version templated on any kind of iterator:
#include <iterator>
#include <algorithm>
template <typename Iterator>
double mean(Iterator begin, Iterator end)
{
if (begin == end)
return 0;
return std::accumulate(begin, end, 0.0) / std::distance(begin, end);
}
Chef
Mean.
Chef has no way to detect EOF, so rather than interpreting
some arbitrary number as meaning "end of input", this program
expects the first input to be the sample size. Pass in the samples
themselves as the other inputs. For example, if you wanted to
compute the mean of 10, 100, 47, you could pass in 3, 10, 100, and
47. To test the "zero-length vector" case, you need to pass in 0.
Ingredients.
0 g Sample Size
0 g Counter
0 g Current Sample
Method.
Take Sample Size from refrigerator.
Put Sample Size into mixing bowl.
Fold Counter into mixing bowl.
Put Current Sample into mixing bowl.
Loop Counter.
Take Current Sample from refrigerator.
Add Current Sample into mixing bowl.
Endloop Counter until looped.
If Sample Size.
Divide Sample Size into mixing bowl.
Put Counter into 2nd mixing bowl.
Fold Sample Size into 2nd mixing bowl.
Endif until ifed.
Pour contents of mixing bowl into baking dish.
Serves 1.
Clojure
Returns a ratio:
(defn mean [sq]
(if (empty? sq)
0
(/ (reduce + sq) (count sq))))
Returns a float:
(defn mean [sq]
(if (empty? sq)
0
(float (/ (reduce + sq) (count sq)))))
COBOL
Intrinsic function:
FUNCTION MEAN(some-table (ALL))
Sample implementation:
IDENTIFICATION DIVISION.
PROGRAM-ID. find-mean.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 i PIC 9(4).
01 summ USAGE FLOAT-LONG.
LINKAGE SECTION.
01 nums-area.
03 nums-len PIC 9(4).
03 nums USAGE FLOAT-LONG
OCCURS 0 TO 1000 TIMES
DEPENDING ON nums-len.
01 result USAGE FLOAT-LONG.
PROCEDURE DIVISION USING nums-area, result.
IF nums-len = 0
MOVE 0 TO result
GOBACK
END-IF
DIVIDE FUNCTION SUM(nums (ALL)) BY nums-len GIVING result
GOBACK
.
Cobra
class Rosetta
def mean(ns as List<of number>) as number
if ns.count == 0
return 0
else
sum = 0.0
for n in ns
sum += n
return sum / ns.count
def main
print "mean of [[]] is [.mean(List<of number>())]"
print "mean of [[1,2,3,4]] is [.mean([1.0,2.0,3.0,4.0])]"
Output:
mean of [] is 0 mean of [1, 2, 3, 4] is 2.5
CoffeeScript
mean = (array) ->
return 0 if array.length is 0
sum = array.reduce (s,i,0) -> s += i
sum / array.length
alert mean [1]
Common Lisp
With Reduce
(defun mean (&rest sequence)
(when sequence
(/ (reduce #'+ sequence) (length sequence))))
With Loop
(defun mean (list)
(when list
(/ (loop for i in list sum i)
(length list))))
Craft Basic
dim a[3, 1, 4, 1, 5, 9]
arraysize s, a
for i = 0 to s - 1
let t = t + a[i]
next i
print t / s
- Output:
3.83
Crystal
# Crystal will return NaN if an empty array is passed
def mean(arr) : Float64
arr.sum / arr.size.to_f
end
D
Imperative Version
real mean(Range)(Range r) pure nothrow @nogc {
real sum = 0.0;
int count;
foreach (item; r) {
sum += item;
count++;
}
if (count == 0)
return 0.0;
else
return sum / count;
}
void main() {
import std.stdio;
int[] data;
writeln("Mean: ", data.mean);
data = [3, 1, 4, 1, 5, 9];
writeln("Mean: ", data.mean);
}
- Output:
mean: 0 mean: 3.83333
More Functional Version
import std.stdio, std.algorithm, std.range;
real mean(Range)(Range r) pure nothrow @nogc {
return r.sum / max(1.0L, r.count);
}
void main() {
writeln("Mean: ", (int[]).init.mean);
writeln("Mean: ", [3, 1, 4, 1, 5, 9].mean);
}
- Output:
Mean: 0 Mean: 3.83333
More Precise Version
A (naive?) version that tries to minimize precision loss (but already the sum algorithm applied to a random access range of floating point values uses a more precise summing strategy):
import std.stdio, std.conv, std.algorithm, std.math, std.traits;
CommonType!(T, real) mean(T)(T[] n ...) if (isNumeric!T) {
alias E = CommonType!(T, real);
auto num = n.dup;
num.schwartzSort!(abs, "a > b");
return num.map!(to!E).sum(0.0L) / max(1, num.length);
}
void main() {
writefln("%8.5f", mean((int[]).init));
writefln("%8.5f", mean( 0, 3, 1, 4, 1, 5, 9, 0));
writefln("%8.5f", mean([-1e20, 3, 1, 4, 1, 5, 9, 1e20]));
}
- Output:
0.00000 2.87500 2.87500
Dart
num mean(List<num> l) => l.reduce((num p, num n) => p + n) / l.length;
void main(){
print(mean([1,2,3,4,5,6,7]));
}
- Output:
4.0
dc
This is not a translation of the bc solution. Array handling would add some complexity. This one-liner is similar to the K solution.
1 2 3 5 7 zsn1k[+z1<+]ds+xln/p
3.6
An expanded example, identifying an empty sample set, could be created as a file, e.g., amean.cd:
[[Nada Mean: ]Ppq]sq
zd0=qsn [stack length = n]sz
1k [precision can be altered]sz
[+z1<+]ds+x[Sum: ]Pp
ln/[Mean: ]Pp
[Sample size: ]Plnp
By saving the sample set "1 2 3 5 7" in a file (sample.dc), the routine, listing summary information, could be called in a command line:
$ dc sample.dc amean.cd
Sum: 18
Mean: 3.6
Sample size: 5
$
Delphi
program AveragesArithmeticMean;
{$APPTYPE CONSOLE}
uses Types;
function ArithmeticMean(aArray: TDoubleDynArray): Double;
var
lValue: Double;
begin
Result := 0;
for lValue in aArray do
Result := Result + lValue;
if Result > 0 then
Result := Result / Length(aArray);
end;
begin
Writeln(Mean(TDoubleDynArray.Create()));
Writeln(Mean(TDoubleDynArray.Create(1,2,3,4,5)));
end.
Dyalect
func avg(args...) {
var acc = .0
var len = 0
for x in args {
len += 1
acc += x
}
acc / len
}
avg(1, 2, 3, 4, 5, 6)
E
Slightly generalized to support any object that allows iteration.
def meanOrZero(numbers) {
var count := 0
var sum := 0
for x in numbers {
sum += x
count += 1
}
return sum / 1.max(count)
}
EasyLang
proc mean . f[] r .
for i = 1 to len f[]
s += f[i]
.
r = s / len f[]
.
f[] = [ 1 2 3 4 5 6 7 8 ]
mean f[] r
print r
EchoLisp
(mean values) is included in math.lib. values may be a list, vector, sequence, or any kind of procrastinator.
(lib 'math)
(mean '(1 2 3 4)) ;; mean of a list
→ 2.5
(mean #(1 2 3 4)) ;; mean of a vector
→ 2.5
(lib 'sequences)
(mean [1 3 .. 10]) ;; mean of a sequence
→ 5
;; error handling
(mean 'elvis)
⛔ error: mean : expected sequence : elvis
(mean ())
💣 error: mean : null is not an object
(mean #())
😐 warning: mean : zero-divide : empty-vector
→ 0
(mean [2 2 .. 2])
😁 warning: mean : zero-divide : empty-sequence
→ 0
ECL
AveVal(SET OF INTEGER s) := AVE(s);
//example usage
SetVals := [14,9,16,20,91];
AveVal(SetVals) //returns 30.0 ;
EDSAC order code
Extends the RC task by finding the arithmetic mean for each of several data sets. Each data set is preceded by the number of data. A count of 0 is not an error but signals that there are no more data sets.
The program needs to avoid the possibility of arithmetic overflow, as pointed out in the F# solution. The moving average used there is not well-suited to EDSAC, on which division had to be done by calling a subroutine. After reading the number of data N, and leaving the trivial case N = 1 for separate treatment, the program first calculates 1/N, then multiplies each value by 1/N before adding it into the result.
[Averages/Arithmetic mean - Rosetta Code]
[EDSAC program (Initial Orders 2) to find and print the average of
a sequence of 35-bit fractional values.
Values are read from tape, preceded by an integer count.]
[Library subroutine M3, runs at load time and is then overwritten.
Prints header; here, last character sets teleprinter to figures.]
PF GK IF AF RD LF UF OF E@ A6F G@ E8F EZ PF
*!!!!!COUNT!!!!!!AVERAGE@&#.. [PZ]
[Main routine: must be at even address]
T214K GK
[0] PF PF [average value]
[2] PF PF [reciprocal of data count]
[4] PF [data count]
[5] PD [17-bit constant 1; also serves as '0' for printing]
[6] @F [carriage return]
[7] &F [line feed]
[8] !F [space]
[9] MF [dot (in figures mode)]
[10] K4096F [teleprinter null]
[Entry and outer loop]
[11] A11@
G56F [call library subroutine R4, sets 0D := data count N]
SD E64@ [exit if N = 0]
T4F [clear acc]
AF T4@ [load and save N (assumed < 2^16)]
[18] A18@ G156F [print N (clears acc)]
TD [clear whole of 0D, including sandwich bit]
T4D [same for 4D]
A4@ S2F [acc := N - 2]
G66@ [jump to special action if N = 1]
A2F [restore N after test]
T5F [store N in 4D high word]
A5@ T1F [store 1 in 0D high word]
[29] A29@ G120F [call library subroutine D6, sets 0D := 0D/4D]
AD T2#@ [load and save 1/N]
T#@ [clear average]
S4@ [load -N]
[Inner loop]
[35] T4@ [update negative loop counter]
[36] A36@ G78F [read next datum to 0D (clears acc)]
H2#@ [mult reg := 1/N]
VD [acc := datum/N]
A#@ T#@ [add into average]
A4@ A5@ [increment negative loop counter]
G35@ [loop until counter = 0]
[45] O8@ O8@ [print 2 spaces]
[Print the average value.
NB: Library subroutine P1 requires non-negative input and prints only the
digits after the decimal point. Formatting has to be done by the caller.]
[47] A#@ [load average (order also serves as minus sign)]
G52@ [jump if average < 0]
TD [pass average to subroutine P1]
O65@ [print plus sign (or could be space)]
E56@ [join common code]
[52] TD [average < 0; clear acc]
S#@ TD [pass abs(average) to subroutine P1]
O47@ [print minus sign]
[56] O5@ O9@ [common code: print '0.']
[58] A58@ G192F [call P1 to print abs(average)]
P8F [8 decimal places]
O6@ O7@ [print CR, LF]
E11@ [loop back always (because acc = 0)]
[Jump to here if data count = 0, means end of data]
[64] O10@ [print null to flush teleprinter buffer]
[65] ZF [halt the machine (order also serves as plus sign)]
[Jump to here if data count = 1]
[66] TF [clear acc]
[67] A67@ G78F [read datum to 0D]
AD T#@ [average := datum]
E45@ [jump to print the average]
[The following puts the entry address into location 50,
so that it can be accessed via the X parameter (see end of program).
This is done in case the data is input from a separate tape.]
T50K P11@ T11Z
[Library subroutine R4.
Input of one signed integer, returned in 0D.]
T56K
GKA3FT21@T4DH6@E11@P5DJFT6FVDL4FA4DTDI4FA4FS5@G7@S5@G20@SDTDT6FEF
[Library subroutine R3.
Input of one long signed decimal fraction, returned in 0D.]
T78K
GKT45KP26@TZA3FTHTDT4DA6HT9@H1HS4HT6FIFAFS4HE7HT7FV4DL8FADT4DA6FA5HG8@
H2#HN4DLDYFTDT28#ZPFT27ZTFP610D@524DP5DPDIFS4HG37@S4DT4DT7FA1HT9@E18@
[Library subroutine D6 - Division, accurate, fast.
36 locations, workspace 6D and 8D.
0D := 0D/4D, where 4D <> 0, -1.]
T120K
GKA3FT34@S4DE13@T4DSDTDE2@T4DADLDTDA4DLDE8@RDU4DLDA35@
T6DE25@U8DN8DA6DT6DH6DS6DN4DA4DYFG21@SDVDTDEFW1526D
[Library subroutine P7: print strictly positive integer in 0D.]
T156K
GKA3FT26@H28#@NDYFLDT4DS27@TFH8@S8@T1FV4DAFG31@SFLDUFOFFFSF
L4FT4DA1FA27@G11@T28#ZPFT27ZP1024FP610D@524D!FO30@SFL8FE22@
[Library subroutine P1: print non-negative fraction in 0D, without '0.']
T192K
GKA18@U17@S20@T5@H19@PFT5@VDUFOFFFSFL4FTDA5@A2FG6@EFU3FJFM1F
[==========================================================================
On the original EDSAC, the following (without the whitespace and comments)
might have been input on a separate tape.]
E25K TX GK
EZ [define entry point]
PF [acc = 0 on entry]
[Counts and data values to be read by library subroutines R3 and R4 respectively.
Note (1) Sign comes *after* value (2) In the data, leading '0.' is omitted.]
7+ 1-2-3-4-5+2-3-
1+ 987654321+
9+ 01+04+09+16+25+36+49+64+81+
9+ 01-04+09-16+25-36+49-64+81-
[Daily minimum temperature (unit = 10 deg. C), Cambridge, UK, January 2000]
31+ 34+14+49+00+04+48+05+48+23-35-07-75+19+03+
26+27+17-06-52+22-17+18+15+03-33-11-04-01-44+89+95+
0+
- Output:
COUNT AVERAGE 7 -0.14285714 1 +0.98765432 9 +0.31666666 9 -0.05000000 31 +0.16774193
Elena
ELENA 6.x:
import extensions;
extension op
{
average()
{
real sum := 0;
int count := 0;
var enumerator := self.enumerator();
while (enumerator.next())
{
sum += *enumerator;
count += 1;
};
^ sum / count
}
}
public program()
{
var array := new int[]{1, 2, 3, 4, 5, 6, 7, 8};
console.printLine(
"Arithmetic mean of {",array.asEnumerable(),"} is ",
array.average()).readChar()
}
- Output:
Arithmetic mean of {1,2,3,4,5,6,7,8} is 4.5
Elixir
defmodule Average do
def mean(list), do: Enum.sum(list) / length(list)
end
Emacs Lisp
(defun mean (lst)
(/ (float (apply '+ lst)) (length lst)))
(mean '(1 2 3 4))
(let ((x '(1 2 3 4)))
(calc-eval "vmean($1)" nil (append '(vec) x)))
EMal
fun mean = real by some real values
real sum
int count
for each real value in values
sum += value
++count
end
return when(count == 0, 0.0, sum / count)
end
writeLine(mean())
writeLine(mean(3,1,4,1,5,9))
- Output:
0.0 3.8333333333333333333333333333
Erlang
mean([]) -> 0;
mean(L) -> lists:sum(L)/erlang:length(L).
Euphoria
function mean(sequence s)
atom sum
if length(s) = 0 then
return 0
else
sum = 0
for i = 1 to length(s) do
sum += s[i]
end for
return sum/length(s)
end if
end function
sequence test
test = {1.0, 2.0, 5.0, -5.0, 9.5, 3.14159}
? mean(test)
Excel
Assuming the values are entered in the A column, type into any cell which will not be part of the list:
=AVERAGE(A1:A10)
Assuming 10 values will be entered, alternatively, you can just type:
=AVERAGE(
and then select the start and end cells, not necessarily in the same row or column.
The output for the first expression, for the set {x | 1 <= x <= 10, x E N} is
1 5,5 2 3 4 5 6 7 8 9 10
F#
The following computes the running mean using a tail-recursive approach. If we just sum all the values then divide by the number of values then we will suffer from overflow problems for large lists. See wikipedia about the moving average computation.
let avg (a:float) (v:float) n =
a + (1. / ((float n) + 1.)) * (v - a)
let mean_series list =
let a, _ = List.fold_left (fun (a, n) h -> avg a (float h) n, n + 1) (0., 0) list in
a
Checking this:
> mean_series [1; 8; 2; 8; 1; 7; 1; 8; 2; 7; 3; 6; 1; 8; 100] ;;
val it : float = 10.86666667
> mean_series [] ;;
val it : float = 0.0
We can also make do with the built-in List.average function:
List.average [4;1;7;5;8;4;5;2;1;5;2;5]
Factor
USING: math math.statistics ;
: arithmetic-mean ( seq -- n )
[ 0 ] [ mean ] if-empty ;
Tests:
( scratchpad ) { 2 3 5 } arithmetic-mean >float
3.333333333333333
Fantom
class Main
{
static Float average (Float[] nums)
{
if (nums.size == 0) return 0.0f
Float sum := 0f
nums.each |num| { sum += num }
return sum / nums.size.toFloat
}
public static Void main ()
{
[[,], [1f], [1f,2f,3f,4f]].each |Float[] i|
{
echo ("Average of $i is: " + average(i))
}
}
}
Fish
!vl0=?vl1=?vl&!
v< +<>0n; >n;
>l1)?^&,n;
Must be called with the values pre-populated on the stack, which can be done in the fish.py interpreter with the -v switch:
fish.py mean.fish -v 10 100 47 207.4
which generates:
91.1
Forth
: fmean ( addr n -- f )
0e
dup 0= if 2drop exit then
tuck floats bounds do
i f@ f+
1 floats +loop
0 d>f f/ ;
create test 3e f, 1e f, 4e f, 1e f, 5e f, 9e f,
test 6 fmean f. \ 3.83333333333333
Fortran
In ISO Fortran 90 or later, use the SUM intrinsic, the SIZE intrinsic and the MAX intrinsic (to avoid divide by zero):
real, target, dimension(100) :: a = (/ (i, i=1, 100) /)
real, dimension(5,20) :: b = reshape( a, (/ 5,20 /) )
real, pointer, dimension(:) :: p => a(2:1) ! pointer to zero-length array
real :: mean, zmean, bmean
real, dimension(20) :: colmeans
real, dimension(5) :: rowmeans
mean = sum(a)/size(a) ! SUM of A's elements divided by SIZE of A
mean = sum(a)/max(size(a),1) ! Same result, but safer code
! MAX of SIZE and 1 prevents divide by zero if SIZE == 0 (zero-length array)
zmean = sum(p)/max(size(p),1) ! Here the safety check pays off. Since P is a zero-length array,
! expression becomes "0 / MAX( 0, 1 ) -> 0 / 1 -> 0", rather than "0 / 0 -> NaN"
bmean = sum(b)/max(size(b),1) ! multidimensional SUM over multidimensional SIZE
rowmeans = sum(b,1)/max(size(b,2),1) ! SUM elements in each row (dimension 1)
! dividing by the length of the row, which is the number of columns (SIZE of dimension 2)
colmeans = sum(b,2)/max(size(b,1),1) ! SUM elements in each column (dimension 2)
! dividing by the length of the column, which is the number of rows (SIZE of dimension 1)
FreeBASIC
' FB 1.05.0 Win64
Function Mean(array() As Double) As Double
Dim length As Integer = Ubound(array) - Lbound(array) + 1
If length = 0 Then
Return 0.0/0.0 'NaN
End If
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 IsNaN(number As Double) As Boolean
Return Str(number) = "-1.#IND" ' NaN as a string in FB
End Function
Dim As Integer n, i
Dim As Double num
Print "Sample input and output"
Print
Do
Input "How many numbers are to be input ? : ", n
Loop Until n > 0
Dim vector(1 To N) As Double
Print
For i = 1 to n
Print " Number #"; i; " : ";
Input "", vector(i)
Next
Print
Print "Mean is"; Mean(vector())
Print
Erase vector
num = Mean(vector())
If IsNaN(num) Then
Print "After clearing the vector, the mean is 'NaN'"
End If
Print
Print "Press any key to quit the program"
Sleep
- Output:
Sample input and output How many numbers are to be input ? : 6 Number # 1 : 12 Number # 2 : 18 Number # 3 : 5.6 Number # 4 : 6 Number # 5 : 23 Number # 6 : 17 Mean is 13.6 After clearing the vector, the mean is 'NaN'
Frink
The following works on arrays or sets. If the collection is empty, this returns the special value undef
.
mean[x] := length[x] > 0 ? sum[x] / length[x] : undef
FutureBasic
local fn MeanAverageOfNumberArray( numberArr as CFArrayRef ) as CFStringRef
CFStringRef result = NULL
if len(numberArr) == 0 then result = @"Mean undefined for empty array." : exit fn
result = fn StringWithFormat( @"Mean average of %d numbers: %@", len(numberArr), fn ObjectValueForKeyPath( numberArr, @"@avg.self" ) )
end fn = result
CFArrayRef numberArray
numberArray = @[@1, @2, @3, @4, @5, @6, @7, @8, @9, @10]
print fn MeanAverageOfNumberArray( numberArray )
numberArray = @[@3, @1, @4, @1, @5, @9]
print fn MeanAverageOfNumberArray( numberArray )
HandleEvents
- Output:
Mean average of 10 numbers: 5.5 Man average of 6 numbers: 3.83333333333333333333333333333333333333
GAP
Mean := function(v)
local n;
n := Length(v);
if n = 0 then
return 0;
else
return Sum(v)/n;
fi;
end;
Mean([3, 1, 4, 1, 5, 9]);
# 23/6
GEORGE
R (n) P ;
0
1, n rep (i)
R P +
]
n div
P
Output:
7.000000000000000 1.500000000000000E+0001 1.300000000000000E+0001 8.000000000000000 2.500000000000000E+0001 7.400000000000000E+0001 3.100000000000000E+0001 2.900000000000000E+0001 1.700000000000000E+0001 4.300000000000000E+0001 2.620000000000000E+0001
GFA Basic
This works for arrays of integers.
DIM a%(10)
FOR i%=0 TO 10
a%(i%)=i%*2
PRINT "element ";i%;" is ";a%(i%)
NEXT i%
PRINT "mean is ";@mean(a%)
'
FUNCTION mean(a%)
LOCAL i%,size%,sum
' find size of array,
size%=DIM?(a%())
' return 0 for empty arrays
IF size%<=0
RETURN 0
ENDIF
' find sum of all elements
sum=0
FOR i%=0 TO size%-1
sum=sum+a%(i%)
NEXT i%
' mean is sum over size
RETURN sum/size%
ENDFUNC
Go
A little more elaborate that the task requires. The function "mean" fulfills the task of "a program to find the mean." As a Go idiom, it returns an ok value of true if result m is valid. An ok value of false means the input "vector" (a Go slice) was empty. The fancy accuracy preserving algorithm is a little more than was called more. The program main is a test program demonstrating the ok idiom and several data cases.
package main
import (
"fmt"
"math"
)
func mean(v []float64) (m float64, ok bool) {
if len(v) == 0 {
return
}
// an algorithm that attempts to retain accuracy
// with widely different values.
var parts []float64
for _, x := range v {
var i int
for _, p := range parts {
sum := p + x
var err float64
switch ax, ap := math.Abs(x), math.Abs(p); {
case ax < ap:
err = x - (sum - p)
case ap < ax:
err = p - (sum - x)
}
if err != 0 {
parts[i] = err
i++
}
x = sum
}
parts = append(parts[:i], x)
}
var sum float64
for _, x := range parts {
sum += x
}
return sum / float64(len(v)), true
}
func main() {
for _, v := range [][]float64{
[]float64{}, // mean returns ok = false
[]float64{math.Inf(1), math.Inf(1)}, // answer is +Inf
// answer is NaN, and mean returns ok = true, indicating NaN
// is the correct result
[]float64{math.Inf(1), math.Inf(-1)},
[]float64{3, 1, 4, 1, 5, 9},
// large magnitude numbers cancel. answer is mean of small numbers.
[]float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},
[]float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},
[]float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},
} {
fmt.Println("Vector:", v)
if m, ok := mean(v); ok {
fmt.Printf("Mean of %d numbers is %g\n\n", len(v), m)
} else {
fmt.Println("Mean undefined\n")
}
}
}
- Output:
Vector: [] Mean undefined Vector: [+Inf +Inf] Mean of 2 numbers is +Inf Vector: [+Inf -Inf] Mean of 2 numbers is NaN Vector: [3 1 4 1 5 9] Mean of 6 numbers is 3.8333333333333335 Vector: [1e+20 3 1 4 1 5 9 -1e+20] Mean of 8 numbers is 2.875 Vector: [10 9 8 7 6 5 4 3 2 1 0 0 0 0 0.11] Mean of 15 numbers is 3.674 Vector: [10 20 30 40 50 -100 4.7 -1100] Mean of 8 numbers is -130.6625
Groovy
def avg = { list -> list == [] ? 0 : list.sum() / list.size() }
Test Program:
println avg(0..9)
println avg([2,2,2,4,2])
println avg ([])
Output:
4.5 2.4 0
Haskell
This function works if the element type is an instance of Fractional:
mean :: (Fractional a) => [a] -> a
mean [] = 0
mean xs = sum xs / Data.List.genericLength xs
But some types, e.g. integers, are not Fractional; the following function works for all Real types:
meanReals :: (Real a, Fractional b) => [a] -> b
meanReals = mean . map realToFrac
If you want to avoid keeping the list in memory and traversing it twice:
{-# LANGUAGE BangPatterns #-}
import Data.List (foldl') --'
mean
:: (Real n, Fractional m)
=> [n] -> m
mean xs =
let (s, l) =
foldl' --'
f
(0, 0)
xs
in realToFrac s / l
where
f (!s, !l) x = (s + x, l + 1)
main :: IO ()
main = print $ mean [1 .. 100]
HicEst
REAL :: vec(100) ! no zero-length arrays in HicEst
vec = $ - 1/2 ! 0.5 ... 99.5
mean = SUM(vec) / LEN(vec) ! 50
END
Hy
Returns None if the input is of length zero.
(defn arithmetic-mean [xs]
(if xs
(/ (sum xs) (len xs))))
Icon and Unicon
Sample outputs:
->am 1 2 3 4 5 6 7 4.0 ->am 0 ->
IDL
If truly only the mean is wanted, one could use
x = [3,1,4,1,5,9]
print,mean(x)
But mean() is just a thin wrapper returning the zeroth element of moment() :
print,moment(x)
; ==>
3.83333 8.96667 0.580037 -1.25081
which are mean, variance, skewness and kurtosis.
There are no zero-length vectors in IDL. Every variable has at least one value or otherwise it is <Undefined>.
J
mean=: +/ % #
That is, sum divided by the number of items. The verb also works on higher-ranked arrays. For example:
mean 3 1 4 1 5 9
3.83333
mean $0 NB. $0 is a zero-length vector
0
x=: 20 4 ?@$ 0 NB. a 20-by-4 table of random (0,1) numbers
mean x
0.58243 0.402948 0.477066 0.511155
The computation can also be written as a loop. It is shown here for comparison only and is highly non-preferred compared to the version above.
mean1=: 3 : 0
z=. 0
for_i. i.#y do. z=. z+i{y end.
z % #y
)
mean1 3 1 4 1 5 9
3.83333
mean1 $0
0
mean1 x
0.58243 0.402948 0.477066 0.511155
Java
public static double avg(double... arr) {
double sum = 0.0;
for (double x : arr) {
sum += x;
}
return sum / arr.length;
}
JavaScript
ES5
function mean(array)
{
var sum = 0, i;
for (i = 0; i < array.length; i++)
{
sum += array[i];
}
return array.length ? sum / array.length : 0;
}
alert( mean( [1,2,3,4,5] ) ); // 3
alert( mean( [] ) ); // 0
Using the native function `.forEach()`:
function mean(array) {
var sum = 0;
array.forEach(function(value){
sum += value;
});
return array.length ? sum / array.length : 0;
}
alert( mean( [1,2,3,4,5] ) ); // 3
Using the native function `.reduce()`:
function mean(array) {
return !array.length ? 0
: array.reduce(function(pre, cur, i) {
return (pre * i + cur) / (i + 1);
});
}
alert( mean( [1,2,3,4,5] ) ); // 3
alert( mean( [] ) ); // 0
Extending the `Array` prototype:
Array.prototype.mean = function() {
return !this.length ? 0
: this.reduce(function(pre, cur, i) {
return (pre * i + cur) / (i + 1);
});
}
alert( [1,2,3,4,5].mean() ); // 3
alert( [].mean() ); // 0
function mean(a)
{
return a.length ? Functional.reduce('+', 0, a) / a.length : 0;
}
ES6
(sample => {
// mean :: [Num] => (Num | NaN)
let mean = lst => {
let lng = lst.length;
return lng ? (
lst.reduce((a, b) => a + b, 0) / lng
) : NaN;
};
return mean(sample);
})([1, 2, 3, 4, 5, 6, 7, 8, 9]);
- Output:
5
Joy
DEFINE avg == dup 0. [+] fold swap size 1 max /.
jq
The mean of an array of numbers can be computed by simply writing
add/length
This definition raises an error condition if the array is empty, so it may make sense to define mean as follows, null being jq's null value:
def mean: if length == 0 then null
else add/length
end;
Julia
Julia's built-in mean function accepts AbstractArrays (vector, matrix, etc.)
julia> using Statistics; mean([1,2,3])
2.0
julia> mean(1:10)
5.5
julia> mean([])
ERROR: mean of empty collection undefined: []
K
mean: {(+/x)%#x}
mean 1 2 3 5 7
3.6
mean@!0 / empty array
0.0
Kotlin
Kotlin has builtin functions for some collection types. Example:
fun main(args: Array<String>) {
val nums = doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
println("average = %f".format(nums.average()))
}
KQL
let dataset = datatable(values:real)[
1, 1.5, 3, 5, 6.5];
dataset|summarize avg(values)
Output:
avg_values 3.4
LabVIEW
This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.
Lambdatalk
{def mean
{lambda {:s}
{if {S.empty? :s}
then 0
else {/ {+ :s} {S.length :s}}}}}
{mean {S.serie 0 1000}}
-> 500
langur
The built-in mean() function works with an array, hash, or range of numbers.
We could use fold() to write a function that takes an array and calculates the mean.
val umean = fn x:fold(fn{+}, x) / len(x)
writeln " custom: ", umean([7, 3, 12])
writeln "built-in: ", mean([7, 3, 12])
- Output:
custom: 7.333333333333333333333333333333333 built-in: 7.333333333333333333333333333333333
Lasso
define average(a::array) => {
not #a->size ? return 0
local(x = 0.0)
with i in #a do => { #x += #i }
return #x / #a->size
}
average(array(1,2,5,17,7.4)) //6.48
LFE
1-Arity
(defun mean (data)
(/ (lists:sum data)
(length data)))
Usage:
> (mean '(1 1))
1.0
> (mean '(1 2))
1.5
> (mean '(2 10))
6.0
> (mean '(6 12 18 24 30 36 42 48 54 60 66 72 78))
42.0
n-Arity
Functions in LFE (and Erlang) have set arity, but macros can be used to provide the same use as n-arity functions:
(defmacro mean args
`(/ (lists:sum ,args)
,(length args)))
Usage:
> (mean 42)
42.0
> (mean 18 66)
42.0
> (mean 6 12 18 24 30 36 42 48 54 60 66 72 78)
42.0
Liberty BASIC
total=17
dim nums(total)
for i = 1 to total
nums(i)=i-1
next
for j = 1 to total
sum=sum+nums(j)
next
if total=0 then mean=0 else mean=sum/total
print "Arithmetic mean: ";mean
Limbo
implement Command;
include "sys.m";
sys: Sys;
include "draw.m";
include "sh.m";
init(nil: ref Draw->Context, nil: list of string)
{
sys = load Sys Sys->PATH;
a := array[] of {1.0, 2.0, 500.0, 257.0};
sys->print("mean of a: %f\n", getmean(a));
}
getmean(a: array of real): real
{
n: real = 0.0;
for (i := 0; i < len a; i++)
n += a[i];
return n / (real len a);
}
Lingo
-- v can be (2D) point, (3D) vector or list of integers/floats
on mean (v)
case ilk(v) of
#point: cnt = 2
#vector: cnt = 3
#list: cnt = v.count
otherwise: return
end case
sum = 0
repeat with i = 1 to cnt
sum = sum + v[i]
end repeat
return float(sum)/cnt
end
put mean(point(1, 2.5))
-- 1.7500
put mean(vector(1.2, 4.7, 5.6))
-- 3.8333
put mean([6,12,18,24,30,36,42,48,54,60,66,72,78])
-- 42.0000
LiveCode
Livecode provides arithmeticMean (avg, average) built-in.
average(1,2,3,4,5) -- 3
average(empty) -- 0
Logo
to average :l
if empty? :l [output 0]
output quotient apply "sum :l count :l
end
print average [1 2 3 4] ; 2.5
Logtalk
Logtalk's standard library provides an arithmetic average predicate but we ignore it here. Representing a vector using a list:
:- object(averages).
:- public(arithmetic/2).
% fails for empty vectors
arithmetic([X| Xs], Mean) :-
sum_and_count([X| Xs], 0, Sum, 0, Count),
Mean is Sum / Count.
% use accumulators to make the predicate tail-recursive
sum_and_count([], Sum, Sum, Count, Count).
sum_and_count([X| Xs], Sum0, Sum, Count0, Count) :-
Sum1 is Sum0 + X,
Count1 is Count0 + 1,
sum_and_count(Xs, Sum1, Sum, Count1, Count).
:- end_object.
Sample output:
| ?- averages::arithmetic([1,2,3,4,5,6,7,8,9,10], Mean).
Mean = 5.5
yes
LSL
integer MAX_ELEMENTS = 10;
integer MAX_VALUE = 100;
default {
state_entry() {
list lst = [];
integer x = 0;
for(x=0 ; x<MAX_ELEMENTS ; x++) {
lst += llFrand(MAX_VALUE);
}
llOwnerSay("lst=["+llList2CSV(lst)+"]");
llOwnerSay("Geometric Mean: "+(string)llListStatistics(LIST_STAT_GEOMETRIC_MEAN, lst));
llOwnerSay(" Max: "+(string)llListStatistics(LIST_STAT_MAX, lst));
llOwnerSay(" Mean: "+(string)llListStatistics(LIST_STAT_MEAN, lst));
llOwnerSay(" Median: "+(string)llListStatistics(LIST_STAT_MEDIAN, lst));
llOwnerSay(" Min: "+(string)llListStatistics(LIST_STAT_MIN, lst));
llOwnerSay(" Num Count: "+(string)llListStatistics(LIST_STAT_NUM_COUNT, lst));
llOwnerSay(" Range: "+(string)llListStatistics(LIST_STAT_RANGE, lst));
llOwnerSay(" Std Dev: "+(string)llListStatistics(LIST_STAT_STD_DEV, lst));
llOwnerSay(" Sum: "+(string)llListStatistics(LIST_STAT_SUM, lst));
llOwnerSay(" Sum Squares: "+(string)llListStatistics(LIST_STAT_SUM_SQUARES, lst));
}
}
Output:
lst=[23.815209, 85.890704, 10.811144, 31.522696, 54.619416, 12.211729, 42.964463, 87.367889, 7.106129, 18.711078] Geometric Mean: 27.325070 Max: 87.367889 Mean: 37.502046 Median: 27.668953 Min: 7.106129 Num Count: 10.000000 Range: 80.261761 Std Dev: 29.819840 Sum: 375.020458 Sum Squares: 22067.040048
Lua
function mean (numlist)
if type(numlist) ~= 'table' then return numlist end
num = 0
table.foreach(numlist,function(i,v) num=num+v end)
return num / #numlist
end
print (mean({3,1,4,1,5,9}))
Lucid
avg(x)
where
sum = first(x) fby sum + next(x);
n = 1 fby n + 1;
avg = sum / n;
end
M4
M4 handle only integers, so in order to have a slightly better math for the mean, we must pass to the mean macro integers multiplied by 100. The macro rmean could embed the macro fmean and extractdec directly, but it is a little bit clearer to keep them separated.
define(`extractdec', `ifelse(eval(`$1%100 < 10'),1,`0',`')eval($1%100)')dnl
define(`fmean', `eval(`($2/$1)/100').extractdec(eval(`$2/$1'))')dnl
define(`mean', `rmean(`$#', $@)')dnl
define(`rmean', `ifelse(`$3', `', `fmean($1,$2)',dnl
`rmean($1, eval($2+$3), shift(shift(shift($@))))')')dnl
mean(0,100,200,300,400,500,600,700,800,900,1000)
Maple
This version accepts any indexable structure, including numeric arrays. We use a call to the "environment variable" (dynamically scoped global) "Normalizer" to provide normalization of symbolic expressions. This can be set by the caller to adjust the strength of normalization desired.
mean := proc( a :: indexable )
local i;
Normalizer( add( i, i in a ) / numelems( a ) )
end proc:
For example:
> mean( { 1/2, 2/3, 3/4, 4/5, 5/6 } ); # set
71
---
100
> mean( [ a, 2, c, 2.3, e ] ); # list
0.8600000000 + a/5 + c/5 + e/5
> mean( Array( [ 1, sin( s ), 3, exp( I*t ), 5 ] ) ); # array
9/5 + 1/5 sin(s) + 1/5 exp(t I)
> mean( [ sin(s)^2, cos(s)^2 ] );
2 2
1/2 sin(s) + 1/2 cos(s)
> Normalizer := simplify: # use a stronger normalizer than the default
> mean( [ sin(s)^2, cos(s)^2 ] );
1/2
> mean([]); # empty argument causes an exception to be raised.
Error, (in mean) numeric exception: division by zero
A slightly different design computes the mean of all its arguments, instead of requiring a single container argument. This seems a little more Maple-like for a general purpose utility.
mean := () -> Normalizer( `+`( args ) / nargs ):
This can be called as in the following examples.
> mean( 1, 2, 3, 4, 5 );
3
> mean( a + b, b + c, c + d, d + e, e + a );
2 a 2 b 2 c 2 d 2 e
--- + --- + --- + --- + ---
5 5 5 5 5
> mean(); # again, an exception is raised
Error, (in mean) numeric exception: division by zero
If desired, we can add argument type-checking as follows.
mean := ( s :: seq(algebraic) ) -> Normalizer( `+`( args ) / nargs ):
Mathematica / Wolfram Language
Modify the built-in Mean function to give 0 for empty vectors (lists in Mathematica):
Unprotect[Mean];
Mean[{}] := 0
Examples:
Mean[{3,4,5}]
Mean[{3.2,4.5,5.9}]
Mean[{-4, 1.233}]
Mean[{}]
Mean[{1/2,1/3,1/4,1/5}]
Mean[{a,c,Pi,-3,a}]
gives (a set of integers gives back an integer or a rational, a set of floats gives back a float, a set of rationals gives a rational back, a list of symbols and numbers keeps the symbols exact and a mix of exact and approximate numbers gives back an approximate number):
4
4.53333
-1.3835
0
77/240
1/5 (-3+2 a+c+Pi)
Mathprog
Summing the vector and then dividing the sum by the vector's length is slightly less boring than calling a builtin function Mean or similar.
Mathprog is never boring so this program finds a number M such that when M is subtracted from each value in the vector a second vector is formed with the property that the sum of the elements in the second vector is zero. In this case M is the Arithmetic Mean.
Euclid proved that for any vector there is only one such number and from this derived the Division Theorem.
To make it more interesting I find the Arithmectic Mean of more than a million Integers.
/*Arithmetic Mean of a large number of Integers
- or - solve a very large constraint matrix
over 1 million rows and columns
Nigel_Galloway
March 18th., 2008.
*/
param e := 20;
set Sample := {1..2**e-1};
var Mean;
var E{z in Sample};
/* sum of variances is zero */
zumVariance: sum{z in Sample} E[z] = 0;
/* Mean + variance[n] = Sample[n] */
variances{z in Sample}: Mean + E[z] = z;
solve;
printf "The arithmetic mean of the integers from 1 to %d is %f\n", 2**e-1, Mean;
end;
When run this produces:
GLPSOL: GLPK LP/MIP Solver, v4.47
Parameter(s) specified in the command line:
--nopresol --math AM.mprog
Reading model section from AM.mprog...
24 lines were read
Generating zumVariance...
Generating variances...
Model has been successfully generated
Scaling...
A: min|aij| = 1.000e+000 max|aij| = 1.000e+000 ratio = 1.000e+000
Problem data seem to be well scaled
Constructing initial basis...
Size of triangular part = 1048575
GLPK Simplex Optimizer, v4.47
1048576 rows, 1048576 columns, 3145725 non-zeros
0: obj = 0.000000000e+000 infeas = 5.498e+011 (1)
* 1: obj = 0.000000000e+000 infeas = 0.000e+000 (0)
OPTIMAL SOLUTION FOUND
Time used: 2.0 secs
Memory used: 1393.8 Mb (1461484590 bytes)
The arithmetic mean of the integers from 1 to 1048575 is 524288.000000
Model has been successfully processed
MATLAB
function meanValue = findmean(setOfValues)
meanValue = mean(setOfValues);
end
Maxima
load("descriptive");
mean([2, 7, 11, 17]);
MAXScript
fn mean data =
(
total = 0
for i in data do
(
total += i
)
if data.count == 0 then 0 else total as float/data.count
)
print (mean #(3, 1, 4, 1, 5, 9))
Mercury
:- module arithmetic_mean.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module float, list, require.
main(!IO) :-
io.print_line(mean([1.0, 2.0, 3.0, 4.0, 5.0]), !IO).
:- func mean(list(float)) = float.
mean([]) = func_error("mean: emtpy list").
mean(Ns @ [_ | _]) = foldl((+), Ns, 0.0) / float(length(Ns)).
:- end_module arithmetic_mean.
Alternatively, we could use inst subtyping to ensure we get a compilation error if the mean function is called with an empty list.
:- func mean(list(float)::in(non_empty_list)) = (float::out).
mean(Ns) = foldl((+), Ns, 0.0) / float(length(Ns)).
min
Returns nan
for an empty quotation.
(2 3 5) avg puts!
- Output:
3.333333333333333
MiniScript
arr = [ 1, 3, 7, 8, 9, 1 ]
avg = function(arr)
avgNum = 0
for num in arr
avgNum = avgNum + num
end for
return avgNum / arr.len
end function
print avg(arr)
МК-61/52
0 П0 П1 С/П ИП0 ИП1 * + ИП1 1
+ П1 / П0 БП 03
Instruction: В/О С/П Number С/П Number ...
Each time you press the С/П on the indicator would mean already entered numbers.
Modula-2
PROCEDURE Avg;
VAR avg : REAL;
BEGIN
avg := sx / n;
InOut.WriteString ("Average = ");
InOut.WriteReal (avg, 8, 2);
InOut.WriteLn
END Avg;
OR
PROCEDURE Average (Data : ARRAY OF REAL; Samples : CARDINAL) : REAL;
(* Calculate the average over 'Samples' values, stored in array 'Data'. *)
VAR sum : REAL;
n : CARDINAL;
BEGIN
sum := 0.0;
FOR n := 0 TO Samples - 1 DO
sum := sum + Data [n]
END;
RETURN sum / FLOAT(Samples)
END Average;
MUMPS
MEAN(X)
;X is assumed to be a list of numbers separated by "^"
QUIT:'$DATA(X) "No data"
QUIT:X="" "Empty Set"
NEW S,I
SET S=0,I=1
FOR QUIT:I>$L(X,"^") SET S=S+$P(X,"^",I),I=I+1
QUIT (S/$L(X,"^"))
USER>W $$MEAN^ROSETTA No data USER>W $$MEAN^ROSETTA("") Empty Set USER> USER>W $$MEAN^ROSETTA("1^6^12^4") 5.75
Nanoquery
def sum(lst)
sum = 0
for n in lst
sum += n
end
return sum
end
def average(x)
return sum(x) / len(x)
end
Nemerle
using System;
using System.Console;
using Nemerle.Collections;
module Mean
{
ArithmeticMean(x : list[int]) : double
{
|[] => 0.0
|_ =>(x.FoldLeft(0, _+_) :> double) / x.Length
}
Main() : void
{
WriteLine("Mean of [1 .. 10]: {0}", ArithmeticMean($[1 .. 10]));
}
}
NetRexx
/* NetRexx */
options replace format comments java crossref symbols nobinary
launchSample()
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method arithmeticMean(vv = Vector) public static signals DivideException returns Rexx
sum = 0
n_ = Rexx
loop n_ over vv
sum = sum + n_
end n_
mean = sum / vv.size()
return mean
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method launchSample() public static
TRUE_ = 1 == 1
FALSE_ = \TRUE_
tracing = FALSE_
vectors = getSampleData()
loop v_ = 0 to vectors.length - 1
say 'Average of:' vectors[v_].toString()
do
say ' =' arithmeticMean(vectors[v_])
catch dex = DivideException
say 'Caught "Divide By Zero"; bypassing...'
if tracing then dex.printStackTrace()
catch xex = RuntimeException
say 'Caught unspecified run-time exception; bypassing...'
if tracing then xex.printStackTrace()
end
say
end v_
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method getSampleData() private static returns Vector[]
seed = 1066
rng = Random(seed)
vectors =[ -
Vector(Arrays.asList([Rexx 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])), -
Vector(), -
Vector(Arrays.asList([Rexx rng.nextInt(seed), rng.nextInt(seed), rng.nextInt(seed), rng.nextInt(seed), rng.nextInt(seed), rng.nextInt(seed)])), -
Vector(Arrays.asList([Rexx rng.nextDouble(), rng.nextDouble(), rng.nextDouble(), rng.nextDouble(), rng.nextDouble(), rng.nextDouble(), rng.nextDouble()])), -
Vector(Arrays.asList([Rexx '1.0', '2.0', 3.0])), -
Vector(Arrays.asList([Rexx '1.0', 'not a number', 3.0])) -
]
return vectors
Output:
Average of: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] = 5.5 Average of: [] Caught "Divide By Zero"; bypassing... Average of: [294, 726, 945, 828, 1031, 825] = 774.833333 Average of: [0.3318379308729921, 0.7612271993941618, 0.9517290891755477, 0.7687823629521795, 0.2201768257213939, 0.1083471020993242, 0.5158554699332363] = 0.52256514 Average of: [1.0, 2.0, 3.0] = 2 Average of: [1.0, not a number, 3.0] Caught unspecified run-time exception; bypassing...
NewLISP
(define (Mean Lst)
(if (empty? Lst)
0
(/ (apply + Lst) (length Lst))))
(Mean (sequence 1 1000))-> 500
(Mean '()) -> 0
Nial
in the standard way, mean is
mean is / [sum, tally]
mean 6 2 4
= 4
but it fails with 0 length vectors. so using a tally with a minimum value 1
dtally is recur [ empty rest, 1 first, 1 first, plus, rest ]
mean is / [sum, dtally]
mean []
=0
Nim
import strutils
proc mean(xs: openArray[float]): float =
for x in xs:
result += x
result = result / float(xs.len)
var v = @[1.0, 2.0, 2.718, 3.0, 3.142]
for i in 0..5:
echo "mean of first ", v.len, " = ", formatFloat(mean(v), precision = 0)
if v.len > 0: v.setLen(v.high)
Output:
mean of first 5 = 2.372 mean of first 4 = 2.1795 mean of first 3 = 1.906 mean of first 2 = 1.5 mean of first 1 = 1 mean of first 0 = -1.#IND
Niue
[ [ , len 1 - at ! ] len 3 - times swap , ] 'map ; ( a Lisp like map, to sum the stack )
[ len 'n ; [ + ] 0 n swap-at map n / ] 'avg ;
1 2 3 4 5 avg .
=> 3
3.4 2.3 .01 2.0 2.1 avg .
=> 1.9619999999999997
Oberon-2
Oxford Oberon-2
MODULE AvgMean;
IMPORT Out;
CONST MAXSIZE = 10;
PROCEDURE Avg(a: ARRAY OF REAL; items: INTEGER): REAL;
VAR
i: INTEGER;
total: REAL;
BEGIN
total := 0.0;
FOR i := 0 TO LEN(a) - 1 DO
total := total + a[i]
END;
RETURN total/LEN(a)
END Avg;
VAR
ary: ARRAY MAXSIZE OF REAL;
BEGIN
ary[0] := 10.0;
ary[1] := 11.01;
ary[2] := 12.02;
ary[3] := 13.03;
ary[4] := 14.04;
ary[5] := 15.05;
ary[6] := 16.06;
ary[7] := 17.07;
ary[8] := 18.08;
ary[9] := 19.09;
Out.Fixed(Avg(ary),4,2);Out.Ln
END AvgMean.
Output:
14.55
Objeck
function : native : PrintAverage(values : FloatVector) ~ Nil {
values->Average()->PrintLine();
}
OCaml
These functions return a float:
let mean_floats = function
| [] -> 0.
| xs -> List.fold_left (+.) 0. xs /. float_of_int (List.length xs)
let mean_ints xs = mean_floats (List.map float_of_int xs)
the previous code is easier to read and understand, though if you wish the fastest implementation to use in production code notice several points: it is possible to save a call to List.length computing the length through the List.fold_left, and for mean_ints it is possible to save calling float_of_int on every numbers, converting only the result of the addition. (also when using List.map and when the order is not important, you can use List.rev_map instead to save an internal call to List.rev). Also the task asks to return 0 on empty lists, but in OCaml this case would rather be handled by an exception.
let mean_floats xs =
if xs = [] then
invalid_arg "empty list"
else
let total, length =
List.fold_left
(fun (tot,len) x -> (x +. tot), len +. 1.)
(0., 0.) xs
in
(total /. length)
;;
let mean_ints xs =
if xs = [] then
invalid_arg "empty list"
else
let total, length =
List.fold_left
(fun (tot,len) x -> (x + tot), len +. 1.)
(0, 0.) xs
in
(float total /. length)
;;
Octave
GNU Octave has a mean function (from statistics package), but it does not handle an empty vector; an implementation that allows that is:
function m = omean(l)
if ( numel(l) == 0 )
m = 0;
else
m = mean(l);
endif
endfunction
disp(omean([]));
disp(omean([1,2,3]));
If the data contains missing value, encoded as non-a-number:
function m = omean(l)
n = sum(~isnan(l));
l(isnan(l))=0;
s = sum(l);
m = s./n;
end;
Oforth
: avg ( x -- avg )
x sum
x size dup ifZero: [ 2drop null ] else: [ >float / ]
;
- Output:
[1, 2, 2.718, 3, 3.142] avg . 2.372 ok [ ] avg . null ok
ooRexx
call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11)
call testAverage .array~of(10, 20, 30, 40, 50, -100, 4.7, -11e2)
call testAverage .array~new
::routine testAverage
use arg numbers
say "numbers =" numbers~toString("l", ", ")
say "average =" average(numbers)
say
::routine average
use arg numbers
-- return zero for an empty list
if numbers~isempty then return 0
sum = 0
do number over numbers
sum += number
end
return sum/numbers~items
Output:
numbers = 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 average = 5.5 numbers = 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11 average = 3.674 numbers = 10, 20, 30, 40, 50, -100, 4.7, -1100 average = -130.6625 numbers = average = 0
Oz
A version working on floats:
declare
fun {Mean Xs}
{FoldL Xs Number.'+' 0.0} / {Int.toFloat {Length Xs}}
end
in
{Show {Mean [3. 1. 4. 1. 5. 9.]}}
PARI/GP
avg(v)={
if(#v,vecsum(v)/#v)
};
Pascal
Program Mean;
function DoMean(vector: array of double): double;
var
sum: double;
i, len: integer;
begin
sum := 0;
len := length(vector);
if len > 0 then
begin
for i := low(vector) to high(vector) do
sum := sum + vector[i];
sum := sum / len;
end;
DoMean := sum;
end;
const
vector: array [3..8] of double = (3.0, 1.0, 4.0, 1.0, 5.0, 9.0);
var
i: integer;
begin
writeln('Calculating the arithmetic mean of a series of numbers:');
write('Numbers: [ ');
for i := low(vector) to high(vector) do
write (vector[i]:3:1, ' ');
writeln (']');
writeln('Mean: ', DoMean(vector):10:8);
end.
Output:
Calculating the arithmetic mean of a series of numbers: Numbers: [ 3.0 1.0 4.0 1.0 5.0 9.0 ] Mean: 3.83333333
Alternative version using the Math unit:
Program DoMean;
uses math;
const
vector: array [3..8] of double = (3.0, 1.0, 4.0, 1.0, 5.0, 9.0);
var
i: integer;
mean: double;
begin
writeln('Calculating the arithmetic mean of a series of numbers:');
write('Numbers: [ ');
for i := low(vector) to high(vector) do
write (vector[i]:3:1, ' ');
writeln (']');
mean := 0;
if length(vector) > 0 then
mean := sum(vector)/length(vector);
writeln('Mean: ', mean:10:8);
end.
Perl
sub avg {
@_ or return 0;
my $sum = 0;
$sum += $_ foreach @_;
return $sum/@_;
}
print avg(qw(3 1 4 1 5 9)), "\n";
Phix
with javascript_semantics function mean(sequence s) if length(s)=0 then return 0 end if return sum(s)/length(s) end function ? mean({1, 2, 5, -5, -9.5, 3.14159})
Phixmonti
1 2 5 -5 -9.5 3.14159 stklen tolist
len swap sum swap / print
PHP
$nums = array(3, 1, 4, 1, 5, 9);
if ($nums)
echo array_sum($nums) / count($nums), "\n";
else
echo "0\n";
Picat
mean([]) = false.
mean(V) = sum(V) / len(V).
PicoLisp
(de mean (Lst)
(if (atom Lst)
0
(/ (apply + Lst) (length Lst)) ) )
Output:
: (mean (range 1 1000)) -> 500
PL/I
arithmetic_mean = sum(A)/dimension(A,1);
Plain English
To run:
Start up.
Demonstrate finding the arithmetic mean.
Wait for the escape key.
Shut down.
An entry is a thing with a fraction.
A list is some entries.
A sum is a fraction.
A mean is a fraction.
To demonstrate finding the arithmetic mean:
Create an example list.
Write "A list: " then the example list on the console.
Find a mean of the example list.
Write "The list's mean: " then the mean on the console.
Destroy the example list.
To add a fraction to a list:
Allocate memory for an entry.
Put the fraction into the entry's fraction.
Append the entry to the list.
To create an example list:
Add 1/1 to the example list.
Add 2/1 to the example list.
Add 5-1/3 to the example list.
Add 7-1/2 to the example list.
To find a sum of a list:
Put 0 into the sum.
Get an entry from the list.
Loop.
If the entry is nil, exit.
Add the entry's fraction to the sum.
Put the entry's next into the entry.
Repeat.
To find a mean of a list:
Find a sum of the list.
Put the sum divided by the list's count into the mean.
To convert a list to a string:
Get an entry from the list.
Loop.
If the entry is nil, break.
Append the entry's fraction to the string.
If the entry's next is not nil, append ", " to the string.
Put the entry's next into the entry.
Repeat.
- Output:
A list: 1, 2, 5-1/3, 7-1/2 The list's mean: 3-23/24
Pop11
define mean(v);
lvars n = length(v), i, s = 0;
if n = 0 then
return(0);
else
for i from 1 to n do
s + v(i) -> s;
endfor;
endif;
return(s/n);
enddefine;
PostScript
/findmean{
/x exch def
/sum 0 def
/i 0 def
x length 0 eq
{}
{
x length{
/sum sum x i get add def
/i i 1 add def
}repeat
/sum sum x length div def
}ifelse
sum ==
}def
/avg {
dup length
{0 gt} {
exch 0 {add} fold exch div
} {
exch pop
} ifte
}.
PowerShell
The hard way by calculating a sum and dividing:
function mean ($x) {
if ($x.Count -eq 0) {
return 0
} else {
$sum = 0
foreach ($i in $x) {
$sum += $i
}
return $sum / $x.Count
}
}
or, shorter, by using the Measure-Object
cmdlet which already knows how to compute an average:
function mean ($x) {
if ($x.Count -eq 0) {
return 0
} else {
return ($x | Measure-Object -Average).Average
}
}
Processing
float mean(float[] arr) {
float out = 0;
for (float n : arr) {
out += n;
}
return out / arr.length;
}
Prolog
mean(List, Mean) :-
length(List, Length),
sumlist(List, Sum),
Mean is Sum / Length.
PureBasic
Procedure.d mean(List number())
Protected sum=0
ForEach number()
sum + number()
Next
ProcedureReturn sum / ListSize(number())
; Depends on programm if zero check needed, returns nan on division by zero
EndProcedure
Python
.
Uses fsum which tracks multiple partial sums to avoid losing precision
from math import fsum
def average(x):
return fsum(x)/float(len(x)) if x else 0
print (average([0,0,3,1,4,1,5,9,0,0]))
print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))
- Output:
2.3
2.3
def average(x):
return sum(x)/float(len(x)) if x else 0
print (average([0,0,3,1,4,1,5,9,0,0]))
print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))
- Output:
(Notice how the second call gave the wrong result)
2.3
1e-21
def avg(data):
if len(data)==0:
return 0
else:
return sum(data)/float(len(data))
print avg([0,0,3,1,4,1,5,9,0,0])
- Output:
2.3
Since 3.4, Python has a [statistics library in the stdlib, which takes care of these precision overflow issues in a way that works for all standard types, not just float, even with values way too big or small to fit in a float. (For Python 2.6-2.7, there's a backport available on PyPI.)
>>> from statistics import mean
>>> mean([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20])
2.3
>>> mean([10**10000, -10**10000, 3, 1, 4, 1, 5, 9, 0, 0])
2.3
>>> mean([10**10000, -10**10000, 3, 1, 4, 1, 5, 9, Fraction(1, 10**10000), Fraction(-1, 10**10000)])
Fraction(23, 10)
>>> big = 10**10000
>>> mean([Decimal(big), Decimal(-big), 3, 1, 4, 1, 5, 9, 1/Decimal(big), -1/Decimal(big)])
Decimal('2.3')
Q
A built-in solution is avg. An implementation of it could be:
mean:{(sum x)%count x}
Quackery
Using the Quackery big number rational arithmetic library bigrat.qky
.
[ $ 'bigrat.qky' loadfile ] now!
[ [] swap times
[ 20001 random 10000 -
n->v 100 n->v v/
join nested join ] ] is makevector ( --> [ )
[ witheach
[ unpack
2 point$ echo$
i 0 > if
[ say ", " ] ] ] is echodecs ( [ --> )
[ dup size n->v rot
0 n->v rot
witheach
[ unpack v+ ]
2swap v/ ] is arithmean ( [ --> n/d )
[ 5 makevector
say "Internal representation of a randomly generated vector" cr
say "of five rational numbers. They are distributed between" cr
say "-100.00 and +100.00 and are multiples of 0.01."
cr cr dup echo cr cr
say "Shown as decimal fractions."
cr cr dup echodecs cr cr
arithmean
say "Arithmetic mean of vector as a decimal fraction to" cr
say "5 places after the point, as a rounded proper" cr
say "fraction with the denominator not exceeding 10, and" cr
say "finally as a vulgar fraction without rounding." cr cr
2dup 5 point$ echo$
say ", "
2dup proper 10 round improper
proper$ echo$
say ", "
vulgar$ echo$ cr cr
say "The same, but with a vector of 9973 rational numbers," cr
say "20 decimal places and a denominator not exceeding 100." cr cr
9973 makevector arithmean
2dup 20 point$ echo$
say ", "
2dup proper 100 round improper
proper$ echo$
say ", "
vulgar$ echo$ cr ] is demonstrate ( --> )
- Output:
Internal representation of a randomly generated vector of five rational numbers. They are distributed between -100.00 and +100.00 and are multiples of 0.01. [ [ -1999 100 ] [ 253 50 ] [ 2867 50 ] [ 3929 50 ] [ -25 2 ] ] Shown as decimal fractions. -19.99, 5.06, 57.34, 78.58, -12.5 Arithmetic mean of vector as a decimal fraction to 5 places after the point, as a rounded proper fraction with the denominator not exceeding 10, and finally as a vulgar fraction without rounding. 21.698, 21 7/10, 10849/500 The same, but with a vector of 9973 rational numbers, 20 decimal places and a denominator not exceeding 100. -0.41664995487817106187, -5/12, -16621/39892
R
R has its mean function but it does not allow for NULL (void vectors or whatever) as argument: in this case it raises a warning and the result is NA. An implementation that does not suppress the warning could be:
omean <- function(v) {
m <- mean(v)
ifelse(is.na(m), 0, m)
}
Racket
Racket's math library (available in v5.3.2 and newer) comes with a mean function that works on arbitrary sequences.
#lang racket
(require math)
(mean (in-range 0 1000)) ; -> 499 1/2
(mean '(2 2 4 4)) ; -> 3
(mean #(3 4 5 8)) ; -> 5
Raku
(formerly Perl 6)
multi mean([]){ Failure.new('mean on empty list is not defined') }; # Failure-objects are lazy exceptions
multi mean (@a) { ([+] @a) / @a }
Rapira
fun mean(arr)
sum := 0
for N from 1 to #arr do
sum := sum + arr[N]
od
return (sum / #arr)
end
REBOL
rebol [
Title: "Arithmetic Mean (Average)"
URL: http://rosettacode.org/wiki/Average/Arithmetic_mean
]
average: func [v /local sum][
if empty? v [return 0]
sum: 0
forall v [sum: sum + v/1]
sum / length? v
]
; Note precision loss as spread increased.
print [mold x: [] "->" average x]
print [mold x: [3 1 4 1 5 9] "->" average x]
print [mold x: [1000 3 1 4 1 5 9 -1000] "->" average x]
print [mold x: [1e20 3 1 4 1 5 9 -1e20] "->" average x]
Output:
[] -> 0 [3 1 4 1 5 9] -> 3.83333333333333 [1000 3 1 4 1 5 9 -1000] -> 2.875 [1E+20 3 1 4 1 5 9 -1E+20] -> 0.0
Red
Red comes with the average
function.
Red ["Arithmetic mean"]
print average []
print average [2 3 5]
- Output:
none 3.333333333333334
The source code for average
:
average: func [
"Returns the average of all values in a block"
block [block! vector! paren! hash!]
][
if empty? block [return none]
divide sum block to float! length? block
]
ReScript
let arr = [3, 8, 4, 1, 5, 12]
let num = Js.Array.length(arr)
let tot = Js.Array.reduce(\"+", 0, arr)
let mean = float_of_int(tot) /. float_of_int(num)
Js.log(Js.Float.toString(mean))
- Output:
$ bsc arithmean.res > arithmean.js $ node arithmean.js 5.5
REXX
The vectors (list) can contain any valid (REXX) numbers.
A check is made to validate if the numbers in the list are all numeric.
/*REXX program finds the averages/arithmetic mean of several lists (vectors) or CL input*/
parse arg @.1; if @.1='' then do; #=6 /*vector from the C.L.?*/
@.1 = 10 9 8 7 6 5 4 3 2 1
@.2 = 10 9 8 7 6 5 4 3 2 1 0 0 0 0 .11
@.3 = '10 20 30 40 50 -100 4.7 -11e2'
@.4 = '1 2 3 4 five 6 7 8 9 10.1. ±2'
@.5 = 'World War I & World War II'
@.6 = /* ◄─── a null value. */
end
else #=1 /*number of CL vectors.*/
do j=1 for #
say ' numbers = ' @.j
say ' average = ' avg(@.j)
say copies('═', 79)
end /*t*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
avg: procedure; parse arg x; #=words(x) /*#: number of items.*/
if #==0 then return 'N/A: ───[null vector.]' /*No words? Return N/A*/
$=0
do k=1 for #; _=word(x,k) /*obtain a number. */
if datatype(_,'N') then do; $=$+_; iterate; end /*if numeric, then add*/
say left('',40) "***error*** non-numeric: " _; #=#-1 /*error; adjust number*/
end /*k*/
if #==0 then return 'N/A: ───[no numeric values.]' /*No nums? Return N/A*/
return $ / # /*return the average. */
output when using the (internal) lists:
numbers = 10 9 8 7 6 5 4 3 2 1 average = 5.5 ═══════════════════════════════════════════════════════════════════════════════ numbers = 10 9 8 7 6 5 4 3 2 1 0 0 0 0 .11 average = 3.674 ═══════════════════════════════════════════════════════════════════════════════ numbers = 10 20 30 40 50 -100 4.7 -11e2 average = -130.6625 ═══════════════════════════════════════════════════════════════════════════════ numbers = 1 2 3 4 five 6 7 8 9 10.1. ±2 ***error*** non-numeric: five ***error*** non-numeric: 10.1. ***error*** non-numeric: ±2 average = 5 ═══════════════════════════════════════════════════════════════════════════════ numbers = World War I & World War II ***error*** non-numeric: World ***error*** non-numeric: War ***error*** non-numeric: I ***error*** non-numeric: & ***error*** non-numeric: World ***error*** non-numeric: War ***error*** non-numeric: II average = N/A: ───[no numeric values.] ═══════════════════════════════════════════════════════════════════════════════ numbers = average = N/A: ───[null vector.] ═══════════════════════════════════════════════════════════════════════════════
Ring
nums = [1,2,3,4,5,6,7,8,9,10]
sum = 0
see "Average = " + average(nums) + nl
func average numbers
for i = 1 to len(numbers)
sum = sum + nums[i]
next
return sum/len(numbers)
RPL
This is based on the dc version above.
≪ DUP 'N' STO →LIST ΣLIST N / 'N' PURGE ≫ 'AMEAN' STO
or,by using the stack instead of a temporary variable:
≪ →LIST ΣLIST LASTARG SIZE / ≫ 'AMEAN' STO
CLEAR 1 2 3 5 7 DEPTH AMEAN
Hard-working approach
Works for all RPL versions.
≪ DUP SIZE SWAP OVER 0 1 ROT FOR j OVER j GET + NEXT ROT / SWAP DROP ≫
Hard-working approach with local variables
No significant impact on program size or speed, but much more readable
≪ DUP SIZE → vector n ≪ 0 1 n FOR j vector j GET + NEXT n / ≫ ≫
Straightforward approach
The dot product of any vector with [1 1 ... 1] gives the sum of its elements.
≪ SIZE LAST DUP 1 CON DOT SWAP / ≫ 'AMEAN' STO
Using built-in statistics features
Most of the code is dedicated to store the input array according to built-in statistics requirements, which requires a matrix with one line per record. Main benefit of this approach is that you can then easily calculate standard deviation and variance by calling resp. SDEV
and VAR
functions.
≪ { 1 } OVER SIZE + RDM TRN '∑DAT' STO MEAN ≫ 'AMEAN' STO
[ 1 5 0 -4 6 ] AMEAN
- Output:
1: 1.6
Ruby
def mean(nums)
nums.sum(0.0) / nums.size
end
nums = [3, 1, 4, 1, 5, 9]
nums.size.downto(0) do |i|
ary = nums[0,i]
puts "array size #{ary.size} : #{mean(ary)}"
end
- Output:
array size 6 : 3.8333333333333335 array size 5 : 2.8 array size 4 : 2.25 array size 3 : 2.6666666666666665 array size 2 : 2.0 array size 1 : 3.0 array size 0 : NaN
Run BASIC
print "Gimme the number in the array:";input numArray
dim value(numArray)
for i = 1 to numArray
value(i) = i * 1.5
next
for i = 1 to total
totValue = totValue +value(numArray)
next
if totValue <> 0 then mean = totValue/numArray
print "The mean is: ";mean
Rust
fn sum(arr: &[f64]) -> f64 {
arr.iter().fold(0.0, |p,&q| p + q)
}
fn mean(arr: &[f64]) -> f64 {
sum(arr) / arr.len() as f64
}
fn main() {
let v = &[2.0, 3.0, 5.0, 7.0, 13.0, 21.0, 33.0, 54.0];
println!("mean of {:?}: {:?}", v, mean(v));
let w = &[];
println!("mean of {:?}: {:?}", w, mean(w));
}
Output:
mean of [2, 3, 5, 7, 13, 21, 33, 54]: 17.25 mean of []: NaN
Sather
Built to work with VEC, ("geometric" vectors), whose elements must be floats. A 0-dimension vector yields "nan".
class VECOPS is
mean(v:VEC):FLT is
m ::= 0.0;
loop m := m + v.aelt!; end;
return m / v.dim.flt;
end;
end;
class MAIN is
main is
v ::= #VEC(|1.0, 5.0, 7.0|);
#OUT + VECOPS::mean(v) + "\n";
end;
end;
Scala
Using Scala 2.7, this has to be defined for each numeric type:
def mean(s: Seq[Int]) = s.foldLeft(0)(_+_) / s.size
However, Scala 2.8 gives much more flexibility, but you still have to opt between integral types and fractional types. For example:
def mean[T](s: Seq[T])(implicit n: Integral[T]) = {
import n._
s.foldLeft(zero)(_+_) / fromInt(s.size)
}
This can be used with any subclass of Sequence on integral types, up to and including BigInt. One can also create singletons extending Integral for user-defined numeric classes. Likewise, Integral can be replaced by Fractional in the code to support fractional types, such as Float and Double.
Alas, Scala 2.8 also simplifies the task in another way:
def mean[T](s: Seq[T])(implicit n: Fractional[T]) = n.div(s.sum, n.fromInt(s.size))
Here we show a function that supports fractional types. Instead of importing the definitions from n, we are calling them on n itself. And because we did not import them, the implicit definitions that would allow us to use / were not imported as well. Finally, we use sum instead of foldLeft.
Scheme
(define (mean l)
(if (null? l)
0
(/ (apply + l) (length l))))
> (mean (list 3 1 4 1 5 9)) 3 5/6
Seed7
$ include "seed7_05.s7i";
include "float.s7i";
const array float: numVector is [] (1.0, 2.0, 3.0, 4.0, 5.0);
const func float: mean (in array float: numbers) is func
result
var float: result is 0.0;
local
var float: total is 0.0;
var float: num is 0.0;
begin
if length(numbers) <> 0 then
for num range numbers do
total +:= num;
end for;
result := total / flt(length(numbers));
end if;
end func;
const proc: main is func
begin
writeln(mean(numVector));
end func;
SenseTalk
SenseTalk has a built-in average function.
put the average of [12,92,-17,66,128]
put average(empty)
- Output:
56.2 nan
Sidef
func avg(Array list) {
list.len > 0 || return 0
list.sum / list.len
}
say avg([Inf, Inf])
say avg([3,1,4,1,5,9])
say avg([1e+20, 3, 1, 4, 1, 5, 9, -1e+20])
say avg([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0.11])
say avg([10, 20, 30, 40, 50, -100, 4.7, -1100])
- Output:
Inf 3.83333333333333333333333333333333333333333333333 2.875 3.674 -130.6625
Slate
[|:list| (list reduce: #+ `er ifEmpty: [0]) / (list isEmpty ifTrue: [1] ifFalse: [list size])] applyWith: #(3 1 4 1 5 9).
[|:list| (list reduce: #+ `er ifEmpty: [0]) / (list isEmpty ifTrue: [1] ifFalse: [list size])] applyWith: {}.
Smalltalk
| numbers |
numbers := #(1 2 3 4 5 6 7 8).
(numbers isEmpty
ifTrue:[0]
ifFalse: [
(numbers inject: 0 into: [:sumSoFar :eachElement | sumSoFar + eachElement]) / numbers size ]
) displayNl.
However, the empty check can be omitted, as inject returns the injected value for empty collections, and we probably do not care for the average of nothing (i.e. the division by zero exception):
| numbers |
numbers := #(1 2 3 4 5 6 7 8).
( numbers inject: 0 into: [:sumSoFar :eachElement | sumSoFar + eachElement]) / numbers size] ) displayNl.
also, most Smalltalk's collection classes already provide sum and average methods, which makes it:
| numbers |
numbers := #(1 2 3 4 5 6 7 8).
(numbers sum / numbers size) displayNl.
or
| numbers |
numbers := #(1 2 3 4 5 6 7 8).
numbers average displayNl.
SNOBOL4
define('avg(a)i,sum') :(avg_end)
avg i = i + 1; sum = sum + a<i> :s(avg)
avg = 1.0 * sum / prototype(a) :(return)
avg_end
* # Fill arrays
str = '1 2 3 4 5 6 7 8 9 10'; arr = array(10)
loop i = i + 1; str len(p) span('0123456789') . arr<i> @p :s(loop)
empty = array(1) ;* Null vector
* # Test and display
output = '[' str '] -> ' avg(arr)
output = '[ ] -> ' avg(empty)
end
Output:
[1 2 3 4 5 6 7 8 9 10] -> 5.5 [ ] -> 0.
SQL
Tested on Oracle 11gR2, the more limited the tool, the more resourceful one becomes :)
create table "numbers" ("datapoint" integer);
insert into "numbers" select rownum from tab;
select sum("datapoint")/count(*) from "numbers";
...or...
select avg("datapoint") from "numbers";
Standard ML
These functions return a real:
fun mean_reals [] = 0.0
| mean_reals xs = foldl op+ 0.0 xs / real (length xs);
val mean_ints = mean_reals o (map real);
The previous code is easier to read and understand, though if you want
the fastest implementation to use in production code notice several points:
it is possible to save a call to length
computing the length through
the foldl
, and for mean_ints it is possible to save calling
real
on every numbers, converting only the result of the addition.
Also the task asks to return 0 on empty lists, but in Standard ML this case
would rather be handled by an exception.
fun mean_reals [] = raise Empty
| mean_reals xs = let
val (total, length) =
foldl
(fn (x, (tot,len)) => (x + tot, len + 1.0))
(0.0, 0.0) xs
in
(total / length)
end;
fun mean_ints [] = raise Empty
| mean_ints xs = let
val (total, length) =
foldl
(fn (x, (tot,len)) => (x + tot, len + 1.0))
(0, 0.0) xs
in
(real total / length)
end;
Stata
Mean of a dataset variable
Illustration of the mean on the population (in millions) in january 2016 of a few european countries (source Eurostat).
clear all
input str20 country population
Belgium 11311.1
Bulgaria 7153.8
"Czech Republic" 10553.8
Denmark 5707.3
Germany 82175.7
Estonia 1315.9
Ireland 4724.7
Greece 10783.7
end
. mean population
Mean estimation Number of obs = 8
--------------------------------------------------------------
| Mean Std. Err. [95% Conf. Interval]
-------------+------------------------------------------------
population | 16715.75 9431.077 -5585.203 39016.7
--------------------------------------------------------------
. tabstat population, statistic(mean)
variable | mean
-------------+----------
population | 16715.75
------------------------
. quietly summarize population
. display r(mean)
16715.75
Mean in Mata
mata
a=11311.1\7153.8\10553.8\5707.3\
82175.7\1315.9\4724.7\10783.7
mean(a)
16715.75
Swift
func meanDoubles(s: [Double]) -> Double {
return s.reduce(0, +) / Double(s.count)
}
func meanInts(s: [Int]) -> Double {
return meanDoubles(s.map{Double($0)})
}
Tcl
package require Tcl 8.5
proc mean args {
if {[set num [llength $args]] == 0} {return 0}
expr {[tcl::mathop::+ {*}$args] / double($num)}
}
mean 3 1 4 1 5 9 ;# ==> 3.8333333333333335
TI-83 BASIC
Mean(Ans
TI-89 BASIC
Define rcmean(nums) = when(dim(nums) = 0, 0, mean(nums))
Trith
: mean dup empty? [drop 0] [dup [+] foldl1 swap length /] branch ;
[3 1 4 1 5 9] mean
TypeScript
function mean(numbersArr)
{
let arrLen = numbersArr.length;
if (arrLen > 0) {
let sum: number = 0;
for (let i of numbersArr) {
sum += i;
}
return sum/arrLen;
}
else return "Not defined";
}
alert( mean( [1,2,3,4,5] ) );
alert( mean( [] ) );
UNIX Shell
1) First solution with bash (V >= 3), works with floats :
echo "`cat f | paste -sd+ | bc -l` / `cat f | wc -l`" | bc -l
cat f
1
2
4
8
16
-200
echo "`cat f | paste -sd+ | bc -l`/`cat f | wc -l`" | bc -l
-28.16666666666666666666
cat f
1.109434
2
4.5
8.45
16
-200
400.56
echo "`cat f | paste -sd+ | bc -l`/`cat f | wc -l`" |bc -l
33.23134771428571428571
2) This example uses expr, so it only works with integers. It checks that each string in the list is an integer.
mean() {
if expr $# >/dev/null; then
(count=0
sum=0
while expr $# \> 0 >/dev/null; do
sum=`expr $sum + "$1"`
result=$?
expr $result \> 1 >/dev/null && exit $result
count=`expr $count + 1`
shift
done
expr $sum / $count)
else
echo 0
fi
}
printf "test 1: "; mean # 0
printf "test 2: "; mean 300 # 300
printf "test 3: "; mean 300 100 400 # 266
printf "test 4: "; mean -400 400 -1300 200 # -275
printf "test 5: "; mean - # expr: syntax error
printf "test 6: "; mean 1 2 A 3 # expr: non-numeric argument
UnixPipes
Uses ksh93-style process substitution. Also overwrites the file named count in the current directory.
term() {
b=$1;res=$2
echo "scale=5;$res+$b" | bc
}
sum() {
(read B; res=$1;
test -n "$B" && (term $B $res) || (term 0 $res))
}
fold() {
func=$1
(while read a ; do
fold $func | $func $a
done)
}
mean() {
tee >(wc -l > count) | fold sum | xargs echo "scale=5;(1/" $(cat count) ") * " | bc
}
(echo 3; echo 1; echo 4) | mean
Ursa
#
# arithmetic mean
#
decl int<> input
decl int i
for (set i 1) (< i (size args)) (inc i)
append (int args<i>) input
end for
out (/ (+ input) (size input)) endl console
Ursala
There is a library function for means already, although it doesn't cope with empty vectors. A mean function could be defined as shown for this task.
#import nat
#import flo
mean = ~&?\0.! div^/plus:-0. float+ length
#cast %e
example = mean <5.,3.,-2.,6.,-4.>
output:
1.600000e+00
V
[mean
[sum 0 [+] fold].
dup sum
swap size [[1 <] [1]] when /
].
Vala
Using array to hold the numbers of the list:
double arithmetic(double[] list){
double mean;
double sum = 0;
if (list.length == 0)
return 0.0;
foreach(double number in list){
sum += number;
} // foreach
mean = sum / list.length;
return mean;
} // end arithmetic mean
public static void main(){
double[] test = {1.0, 2.0, 5.0, -5.0, 9.5, 3.14159};
double[] zero_len = {};
double mean = arithmetic(test);
double mean_zero = arithmetic(zero_len);
stdout.printf("%s\n", mean.to_string());
stdout.printf("%s\n", mean_zero.to_string());
}
Output:
2.6069316666666666 0
VBA
Private Function mean(v() As Double, ByVal leng As Integer) As Variant
Dim sum As Double, i As Integer
sum = 0: i = 0
For i = 0 To leng - 1
sum = sum + vv
Next i
If leng = 0 Then
mean = CVErr(xlErrDiv0)
Else
mean = sum / leng
End If
End Function
Public Sub main()
Dim v(4) As Double
Dim i As Integer, leng As Integer
v(0) = 1#
v(1) = 2#
v(2) = 2.178
v(3) = 3#
v(4) = 3.142
For leng = 5 To 0 Step -1
Debug.Print "mean[";
For i = 0 To leng - 1
Debug.Print IIf(i, "; " & v(i), "" & v(i));
Next i
Debug.Print "] = "; mean(v, leng)
Next leng
End Sub
- Output:
mean[1; 2; 2,178; 3; 3,142] = 0 mean[1; 2; 2,178; 3] = 0 mean[1; 2; 2,178] = 0 mean[1; 2] = 0 mean[1] = 0 mean[] = Fout 2007
VBScript
Function mean(arr)
size = UBound(arr) + 1
mean = 0
For i = 0 To UBound(arr)
mean = mean + arr(i)
Next
mean = mean/size
End Function
'Example
WScript.Echo mean(Array(3,1,4,1,5,9))
- Output:
3.83333333333333
Vedit macro language
The numeric data is stored in current edit buffer as ASCII strings, one value per line.
#1 = 0 // Sum
#2 = 0 // Count
BOF
While(!At_EOF) {
#1 += Num_Eval(SIMPLE)
#2++
Line(1, ERRBREAK)
}
if (#2) { #1 /= #2 }
Num_Type(#1)
Vim Script
Throws an exception if the list is empty.
function Mean(lst)
if empty(a:lst)
throw "Empty"
endif
let sum = 0.0
for i in a:lst
let sum += i
endfor
return sum / len(a:lst)
endfunction
V (Vlang)
import math
import arrays
fn main() {
for v in [
[]f64{}, // mean returns ok = false
[math.inf(1), math.inf(1)], // answer is +Inf
// answer is NaN, and mean returns ok = true, indicating NaN
// is the correct result
[math.inf(1), math.inf(-1)],
[f64(3), 1, 4, 1, 5, 9],
[f64(10), 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11],
[f64(10), 20, 30, 40, 50, -100, 4.7, -11e2],
] {
println("Vector: $v")
m := arrays.fold(v, 0.0, fn(r f64, v f64) f64 { return r+v })/v.len
println("Mean of $v.len numbers is $m\n")
}
}
- Output:
Vector: [] Mean of 0 numbers is nan Vector: [+inf, +inf] Mean of 2 numbers is +inf Vector: [+inf, -inf] Mean of 2 numbers is nan Vector: [3, 1, 4, 1, 5, 9] Mean of 6 numbers is 3.8333333333333335 Vector: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0.11] Mean of 15 numbers is 3.674 Vector: [10, 20, 30, 40, 50, -100, 4.7, -1100] Mean of 8 numbers is -130.66
Wart
def (mean l)
sum.l / len.l
Example run:
mean '(1 2 3) => 2
WDTE
let s => import 'stream';
let a => import 'arrays';
let mean nums =>
a.stream nums
-> s.reduce [0; 0] (@ s p n => [+ (a.at p 0) 1; + (a.at p 1) n])
-> (@ s p => / (a.at p 1) (a.at p 0));
This is a tad messier than it has to be due to a lack of a way to get the length of an array in WDTE currently.
Usage:
mean [1; 2; 3] -- io.writeln io.stdout;
Output:
2
Wortel
@let {
; using a fork (sum divided-by length)
mean1 @(@sum / #)
; using a function with a named argument
mean2 &a / @sum a #a
[[
!mean1 [3 1 4 1 5 9 2]
!mean2 [3 1 4 1 5 9 2]
]]
}
Returns:
[3.5714285714285716 3.5714285714285716]
Wren
class Arithmetic {
static mean(arr) {
if (arr.count == 0) Fiber.abort("Length must be greater than zero")
return arr.reduce(Fn.new{ |x,y| x+y }) / arr.count
}
}
Arithmetic.mean([1,2,3,4,5]) // 3
XLISP
The specification calls for a function that takes a vector; for convenience, we convert this vector internally to a list. The mean of a zero-length vector is returned as nil, equivalent to the empty list or logical false.
(defun mean (v)
(if (= (vector-length v) 0)
nil
(let ((l (vector->list v)))
(/ (apply + l) (length l)))))
XPL0
code CrLf=9;
code real RlOut=48;
func real Mean(A, N);
real A; int N;
real S; int I;
[if N=0 then return 0.0;
S:= 0.0;
for I:= 0 to N-1 do
S:= S+A(I);
return S/float(N);
]; \Mean
real Test;
[Test:= [1.0, 2.0, 5.0, -5.0, 9.5, 3.14159];
RlOut(0, Mean(Test, 6)); CrLf(0);
]
Output:
2.60693
XSLT
Where $values
is some variable indicating a set of nodes containing numbers, the average is given by the XPath expression:
sum($values) div count($values)
Runnable example
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="text"/>
<xsl:template match="/">
<xsl:variable name="values" select="/*/*"/>
<xsl:value-of select="sum($values) div count($values)"/>
</xsl:template>
</xsl:stylesheet>
Sample input:
<numbers>
<!-- Average is 2.4 -->
<number>1</number>
<number>1</number>
<number>2</number>
<number>3</number>
<number>5</number>
</numbers>
Yorick
func mean(x) {
if(is_void(x)) return 0;
return x(*)(avg);
}
zkl
Converts int to floats (implicitly):
fcn mean(a,b,c,etc){ z:=vm.arglist; z.reduce('+,0.0)/z.len() }
mean(3,1,4,1,5,9); //-->3.83333
mean(); //-->Exception thrown: MathError(NaN (Not a number))
To pass in a vector/list:
fcn meanV(z){ z.reduce('+,0.0)/z.len() }
meanV(T(3,1,4,1,5,9)); // --> 3.83333
Zoea
program: average
case: 1
input: [2,3,10]
output: 5
case: 2
input: [7,11]
output: 9
zonnon
module Averages;
type
Vector = array {math} * of real;
procedure ArithmeticMean(x: Vector): real;
begin
(* sum is a predefined function for mathematical arrays *)
return sum(x)
end ArithmeticMean;
var
x: Vector;
begin
x := new Vector(4);
x := [1.0, 2.3, 3.2, 2.1, 5.3];
write("arithmetic mean: ");writeln(ArithmeticMean(x):10:2)
end Averages.
- Output:
arithmetic mean: 13,9
- Programming Tasks
- Probability and statistics
- 0815
- 11l
- 360 Assembly
- 6502 Assembly
- 8th
- ACL2
- Action!
- Action! Tool Kit
- ActionScript
- Ada
- Aime
- ALGOL 68
- ALGOL W
- AmigaE
- AntLang
- APL
- AppleScript
- Applesoft BASIC
- Arturo
- Astro
- AutoHotkey
- AWK
- Babel
- BASIC
- BBC BASIC
- IS-BASIC
- Bc
- Befunge
- Blz
- Bracmat
- Brat
- Burlesque
- BQN
- C
- C sharp
- C++
- STL
- Chef
- Clojure
- COBOL
- Cobra
- CoffeeScript
- Common Lisp
- Craft Basic
- Crystal
- D
- Dart
- Dc
- Delphi
- Dyalect
- E
- EasyLang
- EchoLisp
- ECL
- EDSAC order code
- Elena
- Elixir
- Emacs Lisp
- Calc
- EMal
- Erlang
- Euphoria
- Excel
- F Sharp
- Factor
- Fantom
- Fish
- Forth
- Fortran
- FreeBASIC
- Frink
- FutureBasic
- GAP
- GEORGE
- GFA Basic
- Go
- Groovy
- Haskell
- HicEst
- Hy
- Icon
- Unicon
- IDL
- J
- Java
- JavaScript
- Functional
- Joy
- Jq
- Julia
- K
- Kotlin
- KQL
- LabVIEW
- Lambdatalk
- Langur
- Lasso
- LFE
- Liberty BASIC
- Limbo
- Lingo
- LiveCode
- Logo
- Logtalk
- LSL
- Lua
- Lucid
- M4
- Maple
- Mathematica
- Wolfram Language
- Mathprog
- MATLAB
- Maxima
- MAXScript
- Mercury
- Min
- MiniScript
- МК-61/52
- Modula-2
- MUMPS
- Nanoquery
- Nemerle
- NetRexx
- NewLISP
- Nial
- Nim
- Niue
- Oberon-2
- Objeck
- OCaml
- Octave
- Oforth
- OoRexx
- Oz
- PARI/GP
- Pascal
- Perl
- Phix
- Phixmonti
- PHP
- Picat
- PicoLisp
- PL/I
- Plain English
- Pop11
- PostScript
- Initlib
- PowerShell
- Processing
- Prolog
- PureBasic
- Python
- Q
- Quackery
- R
- Racket
- Raku
- Rapira
- REBOL
- Red
- ReScript
- REXX
- Ring
- RPL
- Ruby
- Run BASIC
- Rust
- Sather
- Scala
- Scheme
- Seed7
- SenseTalk
- Sidef
- Slate
- Smalltalk
- SNOBOL4
- SQL
- Standard ML
- Stata
- Swift
- Tcl
- TI-83 BASIC
- TI-89 BASIC
- Trith
- TypeScript
- UNIX Shell
- UnixPipes
- UnixPipes examples needing attention
- Examples needing attention
- Ursa
- Ursala
- V
- Vala
- VBA
- VBScript
- Vedit macro language
- Vim Script
- V (Vlang)
- Wart
- WDTE
- Wortel
- Wren
- XLISP
- XPL0
- XSLT
- Yorick
- Zkl
- Zoea
- Zonnon
- Pages with too many expensive parser function calls