Averages/Arithmetic mean: Difference between revisions
Content added Content deleted
m (→{{header|Common Lisp}}: Corrected indentation) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
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 28: | Line 28: | ||
=={{header|11l}}== |
=={{header|11l}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang=11l>F average(x) |
||
R sum(x) / Float(x.len) |
R sum(x) / Float(x.len) |
||
print(average([0, 0, 3, 1, 4, 1, 5, 9, 0, 0]))</ |
print(average([0, 0, 3, 1, 4, 1, 5, 9, 0, 0]))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 39: | Line 39: | ||
=={{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 65: | 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 72: | 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 111: | 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 124: | 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 131: | 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 143: | Line 143: | ||
(mv-let (n d) |
(mv-let (n d) |
||
(mean-r xs) |
(mean-r xs) |
||
(/ n d))))</ |
(/ n d))))</syntaxhighlight> |
||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
{{libheader|Action! Tool Kit}} |
{{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) |
PROC Mean(INT ARRAY a INT count REAL POINTER result) |
||
Line 191: | Line 191: | ||
Test(a3,1) |
Test(a3,1) |
||
Test(a3,0) |
Test(a3,0) |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Arithmetic_mean.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Arithmetic_mean.png Screenshot from Atari 8-bit computer] |
||
Line 202: | Line 202: | ||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
< |
<syntaxhighlight lang=ActionScript>function mean(vector:Vector.<Number>):Number |
||
{ |
{ |
||
var sum:Number = 0; |
var sum:Number = 0; |
||
Line 208: | 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. 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. |
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; |
||
Line 233: | Line 233: | ||
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 |
3.83333 |
||
Line 240: | Line 240: | ||
=={{header|Aime}}== |
=={{header|Aime}}== |
||
< |
<syntaxhighlight lang=aime>real |
||
mean(list l) |
mean(list l) |
||
{ |
{ |
||
Line 259: | Line 259: | ||
0; |
0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
Line 267: | 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 279: | 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 303: | 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 321: | 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}}== |
=={{header|AntLang}}== |
||
AntLang has a built-in avg function. |
AntLang has a built-in avg function. |
||
<lang |
<syntaxhighlight lang=AntLang>avg[list]</syntaxhighlight> |
||
=={{header|APL}}== |
=={{header|APL}}== |
||
{{works with|APL2}} |
{{works with|APL2}} |
||
< |
<syntaxhighlight lang=apl> X←3 1 4 1 5 9 |
||
(+/X)÷⍴X |
(+/X)÷⍴X |
||
3.833333333</ |
3.833333333</syntaxhighlight> |
||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
Line 338: | Line 338: | ||
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. |
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) |
set len to (count listOfNumbers) |
||
if (len is 0) then return missing value |
if (len is 0) then return missing value |
||
Line 350: | Line 350: | ||
end average |
end average |
||
average({2500, 2700, 2400, 2300, 2550, 2650, 2750, 2450, 2600, 2400})</ |
average({2500, 2700, 2400, 2300, 2550, 2650, 2750, 2450, 2600, 2400})</syntaxhighlight> |
||
{{output}} |
{{output}} |
||
Line 359: | Line 359: | ||
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 |
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" |
use framework "Foundation" |
||
Line 369: | Line 369: | ||
end average |
end average |
||
average({2500, 2700, 2400, 2300, 2550, 2650, 2750, 2450, 2600, 2400})</ |
average({2500, 2700, 2400, 2300, 2550, 2650, 2750, 2450, 2600, 2400})</syntaxhighlight> |
||
{{output}} |
{{output}} |
||
Line 375: | Line 375: | ||
=={{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 392: | Line 392: | ||
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|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang=rebol>arr: [1 2 3 4 5 6 7] |
||
print average arr</ |
print average arr</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 405: | Line 405: | ||
=={{header|Astro}}== |
=={{header|Astro}}== |
||
< |
<syntaxhighlight lang=astro>mean([1, 2, 3]) |
||
mean(1..10) |
mean(1..10) |
||
mean([]) |
mean([]) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{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 417: | Line 417: | ||
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 444: | Line 444: | ||
print mean(nothing) |
print mean(nothing) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 455: | Line 455: | ||
=={{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 464: | Line 464: | ||
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 475: | Line 475: | ||
ELSE |
ELSE |
||
PRINT 0 |
PRINT 0 |
||
END IF</ |
END IF</syntaxhighlight> |
||
==={{header|BBC BASIC}}=== |
==={{header|BBC BASIC}}=== |
||
Line 481: | Line 481: | ||
To calculate the mean of an array: |
To calculate the mean of an array: |
||
< |
<syntaxhighlight lang=BBC BASIC> |
||
REM specific functions for the array/vector types |
REM specific functions for the array/vector types |
||
Line 510: | Line 510: | ||
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}}=== |
==={{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 |
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) |
120 PRINT AM(ARR) |
||
Line 523: | Line 523: | ||
170 NEXT |
170 NEXT |
||
180 LET AM=T/SIZE(A) |
180 LET AM=T/SIZE(A) |
||
190 END DEF</ |
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 534: | Line 534: | ||
} |
} |
||
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}}== |
=={{header|blz}}== |
||
< |
<syntaxhighlight lang=blz> |
||
:mean(vec) |
:mean(vec) |
||
vec.fold_left(0, (x, y -> x + y)) / vec.length() |
vec.fold_left(0, (x, y -> x + y)) / vec.length() |
||
end</ |
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 574: | Line 574: | ||
| !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 582: | Line 582: | ||
& 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}}== |
=={{header|BQN}}== |
||
Defines a tacit Avg function which works on any simple numeric list. |
Defines a tacit Avg function which works on any simple numeric list. |
||
< |
<syntaxhighlight lang=bqn>Avg ← +´÷≠ |
||
Avg 1‿2‿3‿4</ |
Avg 1‿2‿3‿4</syntaxhighlight> |
||
<lang>2.5</ |
<lang>2.5</syntaxhighlight> |
||
[https://mlochbaum.github.io/BQN/try.html#code=QXZnIOKGkCArwrTDt+KJoAoKQXZnIDHigL8y4oC/M+KAvzQ= Try It!] |
[https://mlochbaum.github.io/BQN/try.html#code=QXZnIOKGkCArwrTDt+KJoAoKQXZnIDHigL8y4oC/M+KAvzQ= Try It!] |
||
Line 613: | Line 613: | ||
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 636: | Line 636: | ||
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 646: | Line 646: | ||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang=csharp>using System; |
||
using System.Linq; |
using System.Linq; |
||
Line 655: | Line 655: | ||
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 686: | Line 686: | ||
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 701: | Line 701: | ||
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 713: | Line 713: | ||
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 726: | Line 726: | ||
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 760: | Line 760: | ||
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 808: | Line 808: | ||
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 826: | Line 826: | ||
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 835: | Line 835: | ||
=={{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 843: | Line 843: | ||
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 |
(when sequence |
||
(/ (reduce #'+ sequence) (length sequence))))</ |
(/ (reduce #'+ sequence) (length sequence))))</syntaxhighlight> |
||
'''With Loop''' |
'''With Loop''' |
||
< |
<syntaxhighlight lang=lisp>(defun mean (list) |
||
(when list |
(when list |
||
(/ (loop for i in list sum i) |
(/ (loop for i in list sum i) |
||
(length list))))</ |
(length list))))</syntaxhighlight> |
||
=={{header|Crystal}}== |
=={{header|Crystal}}== |
||
< |
<syntaxhighlight lang=ruby># Crystal will return NaN if an empty array is passed |
||
def mean(arr) : Float64 |
def mean(arr) : Float64 |
||
arr.sum / arr.size.to_f |
arr.sum / arr.size.to_f |
||
end</ |
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 888: | Line 888: | ||
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 902: | Line 902: | ||
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 909: | Line 909: | ||
===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 922: | Line 922: | ||
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 929: | Line 929: | ||
=={{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 940: | Line 940: | ||
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 |
[+z1<+]ds+x[Sum: ]Pp |
||
ln/[Mean: ]Pp |
ln/[Mean: ]Pp |
||
[Sample size: ]Plnp</ |
[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 982: | Line 982: | ||
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}}== |
=={{header|Dyalect}}== |
||
< |
<syntaxhighlight lang=dyalect>func avg(args...) { |
||
var acc = .0 |
var acc = .0 |
||
var len = 0 |
var len = 0 |
||
Line 996: | Line 996: | ||
} |
} |
||
avg(1, 2, 3, 4, 5, 6)</ |
avg(1, 2, 3, 4, 5, 6)</syntaxhighlight> |
||
=={{header|E}}== |
=={{header|E}}== |
||
Line 1,002: | Line 1,002: | ||
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 1,010: | Line 1,010: | ||
} |
} |
||
return sum / 1.max(count) |
return sum / 1.max(count) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|EasyLang}}== |
=={{header|EasyLang}}== |
||
Line 1,021: | Line 1,021: | ||
f[] = [ 1 2 3 4 5 6 7 8 ] |
f[] = [ 1 2 3 4 5 6 7 8 ] |
||
call mean f[] r |
call mean f[] r |
||
print 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 1,047: | Line 1,047: | ||
😁 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 1,057: | Line 1,057: | ||
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|Elena}}== |
=={{header|Elena}}== |
||
ELENA 5.0: |
ELENA 5.0: |
||
< |
<syntaxhighlight lang=elena>import extensions; |
||
extension op |
extension op |
||
Line 1,088: | Line 1,088: | ||
"Arithmetic mean of {",array.asEnumerable(),"} is ", |
"Arithmetic mean of {",array.asEnumerable(),"} is ", |
||
array.average()).readChar() |
array.average()).readChar() |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,095: | Line 1,095: | ||
=={{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}}== |
||
< |
<syntaxhighlight lang=lisp>(defun mean (lst) |
||
(/ (float (apply '+ lst)) (length lst))) |
(/ (float (apply '+ lst)) (length lst))) |
||
(mean '(1 2 3 4))</ |
(mean '(1 2 3 4))</syntaxhighlight> |
||
{{libheader|Calc}} |
{{libheader|Calc}} |
||
< |
<syntaxhighlight lang=lisp>(let ((x '(1 2 3 4))) |
||
(calc-eval "vmean($1)" nil (append '(vec) x)))</ |
(calc-eval "vmean($1)" nil (append '(vec) x)))</syntaxhighlight> |
||
=={{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 1,129: | Line 1,129: | ||
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 1,159: | Line 1,159: | ||
=={{header|F_Sharp|F#}}== |
=={{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. |
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) |
a + (1. / ((float n) + 1.)) * (v - a) |
||
let mean_series list = |
let mean_series list = |
||
let a, _ = List.fold_left (fun (a, n) h -> avg a (float h) n, n + 1) (0., 0) list in |
let a, _ = List.fold_left (fun (a, n) h -> avg a (float h) n, n + 1) (0., 0) list in |
||
a</ |
a</syntaxhighlight> |
||
Checking this: |
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 |
val it : float = 10.86666667 |
||
> mean_series [] ;; |
> mean_series [] ;; |
||
val it : float = 0.0</ |
val it : float = 0.0</syntaxhighlight> |
||
We can also make do with the built-in ''List.average'' function: |
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 1,207: | Line 1,207: | ||
} |
} |
||
} |
} |
||
</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 1,219: | Line 1,219: | ||
=={{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 1,228: | Line 1,228: | ||
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,251: | Line 1,251: | ||
! 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,297: | Line 1,297: | ||
Print "Press any key to quit the program" |
Print "Press any key to quit the program" |
||
Sleep |
Sleep |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 1,319: | Line 1,319: | ||
=={{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|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang=gap>Mean := function(v) |
||
local n; |
local n; |
||
n := Length(v); |
n := Length(v); |
||
Line 1,335: | Line 1,335: | ||
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,344: | Line 1,344: | ||
] |
] |
||
n div |
n div |
||
P</ |
P</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 1,388: | Line 1,388: | ||
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,457: | Line 1,457: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,483: | Line 1,483: | ||
=={{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,497: | Line 1,497: | ||
=={{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') --' |
||
Line 1,525: | Line 1,525: | ||
main :: IO () |
main :: IO () |
||
main = print $ mean [1 .. 100]</ |
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,557: | Line 1,557: | ||
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,572: | Line 1,572: | ||
=={{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,582: | Line 1,582: | ||
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,596: | Line 1,596: | ||
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) { |
||
double sum = 0.0; |
double sum = 0.0; |
||
for (double x : arr) { |
for (double x : arr) { |
||
Line 1,607: | Line 1,607: | ||
} |
} |
||
return sum / arr.length; |
return sum / arr.length; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
Line 1,613: | Line 1,613: | ||
===ES5=== |
===ES5=== |
||
< |
<syntaxhighlight lang=javascript>function mean(array) |
||
{ |
{ |
||
var sum = 0, i; |
var sum = 0, i; |
||
Line 1,624: | Line 1,624: | ||
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,635: | Line 1,635: | ||
} |
} |
||
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,647: | Line 1,647: | ||
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,659: | Line 1,659: | ||
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,684: | Line 1,684: | ||
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}} |
||
<lang |
<syntaxhighlight lang=JavaScript>5</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}}== |
=={{header|KQL}}== |
||
< |
<syntaxhighlight lang=kql> |
||
let dataset = datatable(values:real)[ |
let dataset = datatable(values:real)[ |
||
1, 1.5, 3, 5, 6.5]; |
1, 1.5, 3, 5, 6.5]; |
||
dataset|summarize avg(values) |
dataset|summarize avg(values) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
Line 1,741: | Line 1,741: | ||
=={{header|Lambdatalk}}== |
=={{header|Lambdatalk}}== |
||
< |
<syntaxhighlight lang=scheme> |
||
{def mean |
{def mean |
||
{lambda {:s} |
{lambda {:s} |
||
Line 1,750: | Line 1,750: | ||
{mean {S.serie 0 1000}} |
{mean {S.serie 0 1000}} |
||
-> 500 |
-> 500 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|langur}}== |
=={{header|langur}}== |
||
Line 1,758: | Line 1,758: | ||
{{works with|langur|0.6.6}} |
{{works with|langur|0.6.6}} |
||
< |
<syntaxhighlight lang=langur>val .mean = f(.x) fold(f{+}, .x) / len(.x) |
||
writeln " custom: ", .mean([7, 3, 12]) |
writeln " custom: ", .mean([7, 3, 12]) |
||
writeln "built-in: ", mean([7, 3, 12])</ |
writeln "built-in: ", mean([7, 3, 12])</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,768: | Line 1,768: | ||
=={{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,775: | Line 1,775: | ||
} |
} |
||
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,781: | Line 1,781: | ||
=== 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,795: | Line 1,795: | ||
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,801: | Line 1,801: | ||
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,826: | Line 1,826: | ||
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}}== |
=={{header|Limbo}}== |
||
< |
<syntaxhighlight lang=Limbo>implement Command; |
||
include "sys.m"; |
include "sys.m"; |
||
Line 1,852: | Line 1,852: | ||
n += a[i]; |
n += a[i]; |
||
return n / (real len a); |
return n / (real len a); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Lingo}}== |
=={{header|Lingo}}== |
||
< |
<syntaxhighlight lang=Lingo>-- v can be (2D) point, (3D) vector or list of integers/floats |
||
on mean (v) |
on mean (v) |
||
case ilk(v) of |
case ilk(v) of |
||
Line 1,868: | Line 1,868: | ||
end repeat |
end repeat |
||
return float(sum)/cnt |
return float(sum)/cnt |
||
end</ |
end</syntaxhighlight> |
||
< |
<syntaxhighlight lang=Lingo>put mean(point(1, 2.5)) |
||
-- 1.7500 |
-- 1.7500 |
||
put mean(vector(1.2, 4.7, 5.6)) |
put mean(vector(1.2, 4.7, 5.6)) |
||
-- 3.8333 |
-- 3.8333 |
||
put mean([6,12,18,24,30,36,42,48,54,60,66,72,78]) |
put mean([6,12,18,24,30,36,42,48,54,60,66,72,78]) |
||
-- 42.0000</ |
-- 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,909: | Line 1,909: | ||
:- 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,939: | Line 1,939: | ||
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,956: | Line 1,956: | ||
=={{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,963: | Line 1,963: | ||
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,980: | Line 1,980: | ||
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> |
||
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> |
||
> 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 2,018: | Line 2,018: | ||
> 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> |
||
> mean( 1, 2, 3, 4, 5 ); |
> mean( 1, 2, 3, 4, 5 ); |
||
3 |
3 |
||
Line 2,033: | Line 2,033: | ||
> 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 2,091: | Line 2,091: | ||
end; |
end; |
||
</syntaxhighlight> |
|||
</lang> |
|||
When run this produces: |
When run this produces: |
||
Line 2,118: | Line 2,118: | ||
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 2,140: | Line 2,140: | ||
) |
) |
||
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 2,162: | Line 2,162: | ||
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}}== |
=={{header|min}}== |
||
Returns <code>nan</code> for an empty quotation. |
Returns <code>nan</code> for an empty quotation. |
||
{{works with|min|0.19.3}} |
{{works with|min|0.19.3}} |
||
< |
<syntaxhighlight lang=min>(((0 (+) reduce) (size /)) cleave) :mean |
||
(2 3 5) mean print</ |
(2 3 5) mean print</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,183: | Line 2,183: | ||
=={{header|MiniScript}}== |
=={{header|MiniScript}}== |
||
< |
<syntaxhighlight lang=MiniScript>arr = [ 1, 3, 7, 8, 9, 1 ] |
||
avg = function(arr) |
avg = function(arr) |
||
Line 2,193: | Line 2,193: | ||
end function |
end function |
||
print avg(arr)</ |
print avg(arr)</syntaxhighlight> |
||
=={{header|МК-61/52}}== |
=={{header|МК-61/52}}== |
||
<lang>0 П0 П1 С/П ИП0 ИП1 * + ИП1 1 |
<lang>0 П0 П1 С/П ИП0 ИП1 * + ИП1 1 |
||
+ П1 / П0 БП 03</ |
+ П1 / П0 БП 03</syntaxhighlight> |
||
''Instruction:'' В/О С/П Number С/П Number ... |
''Instruction:'' В/О С/П Number С/П Number ... |
||
Line 2,204: | Line 2,204: | ||
=={{header|Modula-2}}== |
=={{header|Modula-2}}== |
||
< |
<syntaxhighlight lang=modula2>PROCEDURE Avg; |
||
VAR avg : REAL; |
VAR avg : REAL; |
||
Line 2,213: | Line 2,213: | ||
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 2,228: | Line 2,228: | ||
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 2,238: | Line 2,238: | ||
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 2,250: | Line 2,250: | ||
=={{header|Nanoquery}}== |
=={{header|Nanoquery}}== |
||
< |
<syntaxhighlight lang=Nanoquery>def sum(lst) |
||
sum = 0 |
sum = 0 |
||
for n in lst |
for n in lst |
||
Line 2,260: | Line 2,260: | ||
def average(x) |
def average(x) |
||
return sum(x) / len(x) |
return sum(x) / len(x) |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
< |
<syntaxhighlight lang=Nemerle>using System; |
||
using System.Console; |
using System.Console; |
||
using Nemerle.Collections; |
using Nemerle.Collections; |
||
Line 2,279: | Line 2,279: | ||
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 2,333: | Line 2,333: | ||
] |
] |
||
return vectors |
return vectors |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Output:''' |
'''Output:''' |
||
<pre> |
<pre> |
||
Line 2,357: | Line 2,357: | ||
=={{header|NewLISP}}== |
=={{header|NewLISP}}== |
||
< |
<syntaxhighlight lang=NewLISP>(define (Mean Lst) |
||
(if (empty? Lst) |
(if (empty? Lst) |
||
0 |
0 |
||
Line 2,363: | Line 2,363: | ||
(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: openArray[float]): float = |
proc mean(xs: openArray[float]): float = |
||
Line 2,391: | Line 2,391: | ||
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) |
||
if v.len > 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,401: | Line 2,401: | ||
=={{header|Niue}}== |
=={{header|Niue}}== |
||
< |
<syntaxhighlight 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,409: | Line 2,409: | ||
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,443: | Line 2,443: | ||
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> |
||
Line 2,450: | Line 2,450: | ||
=={{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,475: | Line 2,475: | ||
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,498: | Line 2,498: | ||
in |
in |
||
(float total /. length) |
(float total /. length) |
||
;;</ |
;;</syntaxhighlight> |
||
=={{header|Octave}}== |
=={{header|Octave}}== |
||
Line 2,504: | Line 2,504: | ||
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,513: | Line 2,513: | ||
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 ) |
||
x sum |
x sum |
||
x size dup ifZero: [ 2drop null ] else: [ >float / ] |
x size dup ifZero: [ 2drop null ] else: [ >float / ] |
||
;</ |
;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,540: | Line 2,540: | ||
=={{header|ooRexx}}== |
=={{header|ooRexx}}== |
||
< |
<syntaxhighlight 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,562: | Line 2,562: | ||
end |
end |
||
return sum/numbers~items |
return sum/numbers~items |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 2,580: | Line 2,580: | ||
=={{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,622: | Line 2,622: | ||
writeln (']'); |
writeln (']'); |
||
writeln('Mean: ', DoMean(vector):10:8); |
writeln('Mean: ', DoMean(vector):10:8); |
||
end.</ |
end.</syntaxhighlight> |
||
Output: |
Output: |
||
Line 2,633: | Line 2,633: | ||
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,650: | Line 2,650: | ||
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,660: | Line 2,660: | ||
} |
} |
||
print avg(qw(3 1 4 1 5 9)), "\n";</ |
print avg(qw(3 1 4 1 5 9)), "\n";</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
<!--< |
<!--<syntaxhighlight lang=Phix>(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
||
<span style="color: #008080;">function</span> <span style="color: #000000;">mean</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> |
<span style="color: #008080;">function</span> <span style="color: #000000;">mean</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> |
||
Line 2,671: | Line 2,671: | ||
<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> |
<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}}== |
=={{header|Phixmonti}}== |
||
< |
<syntaxhighlight lang=Phixmonti>1 2 5 -5 -9.5 3.14159 stklen tolist |
||
len swap sum swap / print</ |
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|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)) |
||
Line 2,694: | Line 2,694: | ||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang=pli>arithmetic_mean = sum(A)/dimension(A,1);</syntaxhighlight> |
||
=={{header|Plain English}}== |
=={{header|Plain English}}== |
||
< |
<syntaxhighlight lang=plainenglish>To run: |
||
Start up. |
Start up. |
||
Demonstrate finding the arithmetic mean. |
Demonstrate finding the arithmetic mean. |
||
Line 2,746: | Line 2,746: | ||
If the entry's next is not nil, append ", " to the string. |
If the entry's next is not nil, append ", " to the string. |
||
Put the entry's next into the entry. |
Put the entry's next into the entry. |
||
Repeat.</ |
Repeat.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,755: | Line 2,755: | ||
=={{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,765: | Line 2,765: | ||
endif; |
endif; |
||
return(s/n); |
return(s/n); |
||
enddefine;</ |
enddefine;</syntaxhighlight> |
||
=={{header|PostScript}}== |
=={{header|PostScript}}== |
||
Line 2,784: | Line 2,784: | ||
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,797: | Line 2,797: | ||
} 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,811: | Line 2,811: | ||
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,819: | Line 2,819: | ||
return ($x | Measure-Object -Average).Average |
return ($x | Measure-Object -Average).Average |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Processing}}== |
=={{header|Processing}}== |
||
< |
<syntaxhighlight lang=processing>float mean(float[] arr) { |
||
float out = 0; |
float out = 0; |
||
for (float n : arr) { |
for (float n : arr) { |
||
Line 2,828: | Line 2,828: | ||
} |
} |
||
return out / arr.length; |
return out / arr.length; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
Line 2,834: | Line 2,834: | ||
{{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,850: | Line 2,850: | ||
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}} |
{{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.) |
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]) |
>>> mean([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]) |
||
2.3 |
2.3 |
||
Line 2,900: | Line 2,900: | ||
>>> big = 10**10000 |
>>> big = 10**10000 |
||
>>> mean([Decimal(big), Decimal(-big), 3, 1, 4, 1, 5, 9, 1/Decimal(big), -1/Decimal(big)]) |
>>> mean([Decimal(big), Decimal(-big), 3, 1, 4, 1, 5, 9, 1/Decimal(big), -1/Decimal(big)]) |
||
Decimal('2.3')</ |
Decimal('2.3')</syntaxhighlight> |
||
=={{header|Q}}== |
=={{header|Q}}== |
||
A built-in solution is <tt>avg</tt>. An implementation of it could be: |
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}}== |
=={{header|Quackery}}== |
||
Line 2,910: | Line 2,910: | ||
Using the Quackery big number rational arithmetic library <code>bigrat.qky</code>. |
Using the Quackery big number rational arithmetic library <code>bigrat.qky</code>. |
||
< |
<syntaxhighlight lang=Quackery> [ $ 'bigrat.qky' loadfile ] now! |
||
[ [] swap times |
[ [] swap times |
||
Line 2,961: | Line 2,961: | ||
proper$ echo$ |
proper$ echo$ |
||
say ", " |
say ", " |
||
vulgar$ echo$ cr ] is demonstrate ( --> )</ |
vulgar$ echo$ cr ] is demonstrate ( --> )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,990: | Line 2,990: | ||
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,999: | Line 2,999: | ||
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 3,006: | Line 3,006: | ||
(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}}== |
=={{header|Raku}}== |
||
Line 3,012: | Line 3,012: | ||
{{works with|Rakudo|2015.10-11}} |
{{works with|Rakudo|2015.10-11}} |
||
< |
<syntaxhighlight lang=perl6>multi mean([]){ Failure.new('mean on empty list is not defined') }; # Failure-objects are lazy exceptions |
||
multi mean (@a) { ([+] @a) / @a }</ |
multi mean (@a) { ([+] @a) / @a }</syntaxhighlight> |
||
=={{header|Rapira}}== |
=={{header|Rapira}}== |
||
< |
<syntaxhighlight lang=Rapira>fun mean(arr) |
||
sum := 0 |
sum := 0 |
||
for N from 1 to #arr do |
for N from 1 to #arr do |
||
Line 3,022: | Line 3,022: | ||
od |
od |
||
return (sum / #arr) |
return (sum / #arr) |
||
end</ |
end</syntaxhighlight> |
||
=={{header|REBOL}}== |
=={{header|REBOL}}== |
||
< |
<syntaxhighlight lang=REBOL>rebol [ |
||
Title: "Arithmetic Mean (Average)" |
Title: "Arithmetic Mean (Average)" |
||
URL: http://rosettacode.org/wiki/Average/Arithmetic_mean |
URL: http://rosettacode.org/wiki/Average/Arithmetic_mean |
||
Line 3,043: | Line 3,043: | ||
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 3,054: | Line 3,054: | ||
=={{header|Red}}== |
=={{header|Red}}== |
||
Red comes with the <code>average</code> function. |
Red comes with the <code>average</code> function. |
||
< |
<syntaxhighlight lang=red>Red ["Arithmetic mean"] |
||
print average [] |
print average [] |
||
print average [2 3 5]</ |
print average [2 3 5]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,065: | Line 3,065: | ||
The source code for <code>average</code>: |
The source code for <code>average</code>: |
||
< |
<syntaxhighlight lang=red>average: func [ |
||
"Returns the average of all values in a block" |
"Returns the average of all values in a block" |
||
block [block! vector! paren! hash!] |
block [block! vector! paren! hash!] |
||
Line 3,071: | Line 3,071: | ||
if empty? block [return none] |
if empty? block [return none] |
||
divide sum block to float! length? block |
divide sum block to float! length? block |
||
]</ |
]</syntaxhighlight> |
||
=={{header|ReScript}}== |
=={{header|ReScript}}== |
||
< |
<syntaxhighlight lang=ReScript>let arr = [3, 8, 4, 1, 5, 12] |
||
let num = Js.Array.length(arr) |
let num = Js.Array.length(arr) |
||
Line 3,081: | Line 3,081: | ||
let mean = float_of_int(tot) /. float_of_int(num) |
let mean = float_of_int(tot) /. float_of_int(num) |
||
Js.log(Js.Float.toString(mean))</ |
Js.log(Js.Float.toString(mean))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,093: | Line 3,093: | ||
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 3,119: | Line 3,119: | ||
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 3,154: | Line 3,154: | ||
=={{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 3,164: | Line 3,164: | ||
next |
next |
||
return sum/len(numbers) |
return sum/len(numbers) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|RPL/2}}== |
=={{header|RPL/2}}== |
||
Line 3,170: | Line 3,170: | ||
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. |
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. |
||
< |
<syntaxhighlight lang=rpl/2>1 2 3 5 7 |
||
AMEAN |
AMEAN |
||
<< DEPTH DUP 'N' STO ->LIST ΣLIST N / >> |
<< DEPTH DUP 'N' STO ->LIST ΣLIST N / >> |
||
3.6</ |
3.6</syntaxhighlight> |
||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang=ruby>def mean(nums) |
||
nums.sum(0.0) / nums.size |
nums.sum(0.0) / nums.size |
||
end |
end |
||
Line 3,184: | Line 3,184: | ||
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 3,197: | Line 3,197: | ||
=={{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 3,207: | Line 3,207: | ||
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 3,224: | Line 3,224: | ||
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 3,231: | Line 3,231: | ||
=={{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 3,244: | Line 3,244: | ||
#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 3,267: | Line 3,267: | ||
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 3,275: | Line 3,275: | ||
=={{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 3,284: | Line 3,284: | ||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang=seed7>$ include "seed7_05.s7i"; |
||
include "float.s7i"; |
include "float.s7i"; |
||
Line 3,307: | Line 3,307: | ||
begin |
begin |
||
writeln(mean(numVector)); |
writeln(mean(numVector)); |
||
end func;</ |
end func;</syntaxhighlight> |
||
=={{header|SenseTalk}}== |
=={{header|SenseTalk}}== |
||
SenseTalk has a built-in average function. |
SenseTalk has a built-in average function. |
||
< |
<syntaxhighlight lang=sensetalk>put the average of [12,92,-17,66,128] |
||
put average(empty) |
put average(empty) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,322: | Line 3,322: | ||
=={{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; |
||
Line 3,331: | Line 3,331: | ||
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>inf |
<pre>inf |
||
Line 3,341: | Line 3,341: | ||
=={{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 3,354: | Line 3,354: | ||
(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 3,385: | Line 3,385: | ||
{{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 3,398: | Line 3,398: | ||
output = '[' str '] -> ' avg(arr) |
output = '[' str '] -> ' avg(arr) |
||
output = '[ ] -> ' avg(empty) |
output = '[ ] -> ' avg(empty) |
||
end</ |
end</syntaxhighlight> |
||
Output: |
Output: |
||
Line 3,406: | Line 3,406: | ||
=={{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> |
||
create table "numbers" ("datapoint" integer); |
create table "numbers" ("datapoint" integer); |
||
Line 3,412: | Line 3,412: | ||
select sum("datapoint")/count(*) from "numbers"; |
select sum("datapoint")/count(*) from "numbers"; |
||
</syntaxhighlight> |
|||
</lang> |
|||
...or... |
...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 3,432: | Line 3,432: | ||
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 3,451: | Line 3,451: | ||
in |
in |
||
(real total / length) |
(real total / length) |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|Stata}}== |
=={{header|Stata}}== |
||
Line 3,486: | Line 3,486: | ||
. quietly summarize population |
. quietly summarize population |
||
. display r(mean) |
. display r(mean) |
||
16715.75</ |
16715.75</syntaxhighlight> |
||
=== Mean in Mata === |
=== Mean in Mata === |
||
< |
<syntaxhighlight lang=stata>mata |
||
a=11311.1\7153.8\10553.8\5707.3\ |
a=11311.1\7153.8\10553.8\5707.3\ |
||
82175.7\1315.9\4724.7\10783.7 |
82175.7\1315.9\4724.7\10783.7 |
||
mean(a) |
mean(a) |
||
16715.75</ |
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 3,541: | Line 3,541: | ||
alert( mean( [1,2,3,4,5] ) ); |
alert( mean( [1,2,3,4,5] ) ); |
||
alert( mean( [] ) ); |
alert( mean( [] ) ); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
1) First solution with bash (V >= 3), works with floats : |
1) First solution with bash (V >= 3), works with floats : |
||
< |
<syntaxhighlight lang=bash1>echo "`cat f | paste -sd+ | bc -l` / `cat f | wc -l`" | bc -l |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang=bash1>cat f |
||
1 |
1 |
||
2 |
2 |
||
Line 3,569: | Line 3,569: | ||
echo "`cat f | paste -sd+ | bc -l`/`cat f | wc -l`" |bc -l |
echo "`cat f | paste -sd+ | bc -l`/`cat f | wc -l`" |bc -l |
||
33.23134771428571428571 |
33.23134771428571428571 |
||
</syntaxhighlight> |
|||
</lang> |
|||
2) This example uses <tt>expr</tt>, so it only works with integers. It checks that each string in the list is an integer. |
2) 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 3,596: | Line 3,596: | ||
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}}== |
=={{header|UnixPipes}}== |
||
Line 3,603: | Line 3,603: | ||
Uses [[ksh93]]-style process substitution. Also overwrites the file named <tt>count</tt> in the current directory. |
Uses [[ksh93]]-style process substitution. Also overwrites the file named <tt>count</tt> in the current directory. |
||
{{works with|bash}} |
{{works with|bash}} |
||
< |
<syntaxhighlight lang=bash>term() { |
||
b=$1;res=$2 |
b=$1;res=$2 |
||
echo "scale=5;$res+$b" | bc |
echo "scale=5;$res+$b" | bc |
||
Line 3,624: | Line 3,624: | ||
} |
} |
||
(echo 3; echo 1; echo 4) | mean</ |
(echo 3; echo 1; echo 4) | mean</syntaxhighlight> |
||
=={{header|Ursa}}== |
=={{header|Ursa}}== |
||
< |
<syntaxhighlight lang=ursa># |
||
# arithmetic mean |
# arithmetic mean |
||
# |
# |
||
Line 3,637: | Line 3,637: | ||
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 3,649: | Line 3,649: | ||
#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,688: | Line 3,688: | ||
stdout.printf("%s\n", mean_zero.to_string()); |
stdout.printf("%s\n", mean_zero.to_string()); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
Line 3,697: | Line 3,697: | ||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
< |
<syntaxhighlight lang=vb>Private Function mean(v() As Double, ByVal leng As Integer) As Variant |
||
Dim sum As Double, i As Integer |
Dim sum As Double, i As Integer |
||
sum = 0: i = 0 |
sum = 0: i = 0 |
||
Line 3,724: | Line 3,724: | ||
Debug.Print "] = "; mean(v, leng) |
Debug.Print "] = "; mean(v, leng) |
||
Next leng |
Next leng |
||
End Sub</ |
End Sub</syntaxhighlight>{{out}} |
||
<pre>mean[1; 2; 2,178; 3; 3,142] = 0 |
<pre>mean[1; 2; 2,178; 3; 3,142] = 0 |
||
mean[1; 2; 2,178; 3] = 0 |
mean[1; 2; 2,178; 3] = 0 |
||
Line 3,733: | Line 3,733: | ||
=={{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,745: | Line 3,745: | ||
'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,752: | Line 3,752: | ||
=={{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,761: | Line 3,761: | ||
} |
} |
||
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,774: | Line 3,774: | ||
endfor |
endfor |
||
return sum / len(a:lst) |
return sum / len(a:lst) |
||
endfunction</ |
endfunction</syntaxhighlight> |
||
=={{header|Vlang}}== |
=={{header|Vlang}}== |
||
< |
<syntaxhighlight lang=vlang>import math |
||
import arrays |
import arrays |
||
Line 3,798: | Line 3,798: | ||
println("Mean of $v.len numbers is $m\n") |
println("Mean of $v.len numbers is $m\n") |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Vector: [] |
<pre>Vector: [] |
||
Line 3,819: | Line 3,819: | ||
=={{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,827: | Line 3,827: | ||
=={{header|WDTE}}== |
=={{header|WDTE}}== |
||
< |
<syntaxhighlight lang=WDTE>let s => import 'stream'; |
||
let a => import 'arrays'; |
let a => import 'arrays'; |
||
Line 3,833: | Line 3,833: | ||
a.stream nums |
a.stream nums |
||
-> s.reduce [0; 0] (@ s p n => [+ (a.at p 0) 1; + (a.at p 1) n]) |
-> 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));</ |
-> (@ s p => / (a.at p 1) (a.at p 0));</syntaxhighlight> |
||
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. |
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: |
Usage: |
||
< |
<syntaxhighlight lang=WDTE>mean [1; 2; 3] -- io.writeln io.stdout;</syntaxhighlight> |
||
Output: |
Output: |
||
Line 3,844: | Line 3,844: | ||
=={{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,855: | Line 3,855: | ||
!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}}== |
=={{header|Wren}}== |
||
< |
<syntaxhighlight lang=ecmascript>class Arithmetic { |
||
static mean(arr) { |
static mean(arr) { |
||
if (arr.count == 0) Fiber.abort("Length must be greater than zero") |
if (arr.count == 0) Fiber.abort("Length must be greater than zero") |
||
Line 3,866: | Line 3,866: | ||
} |
} |
||
} |
} |
||
Arithmetic.mean([1,2,3,4,5]) // 3</ |
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,893: | Line 3,893: | ||
[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,904: | Line 3,904: | ||
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,915: | Line 3,915: | ||
<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,926: | Line 3,926: | ||
<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}}== |
=={{header|Zoea}}== |
||
< |
<syntaxhighlight lang=Zoea> |
||
program: average |
program: average |
||
case: 1 |
case: 1 |
||
Line 3,952: | Line 3,952: | ||
input: [7,11] |
input: [7,11] |
||
output: 9 |
output: 9 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|zonnon}}== |
=={{header|zonnon}}== |
||
< |
<syntaxhighlight lang=zonnon> |
||
module Averages; |
module Averages; |
||
type |
type |
||
Line 3,973: | Line 3,973: | ||
write("arithmetic mean: ");writeln(ArithmeticMean(x):10:2) |
write("arithmetic mean: ");writeln(ArithmeticMean(x):10:2) |
||
end Averages. |
end Averages. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |