Averages/Arithmetic mean: Difference between revisions

m
(45 intermediate revisions by 28 users not shown)
Line 1:
{{task|Probability and statistics}}
 
;Task
{{task heading}}
 
Write a program to find the [[wp:arithmetic mean|mean]] (arithmetic average) of a numeric vector.
Line 14:
 
=={{header|0815}}==
<langsyntaxhighlight lang="0815">
{x{+=<:2:x/%<:d:~$<:01:~><:02:~><:03:~><:04:~><:05:~><:06:~><:07:~><:08:
~><:09:~><:0a:~><:0b:~><:0c:~><:0d:~><:0e:~><:0f:~><:10:~><:11:~><:12:~>
<:13:~><:14:~><:15:~><:16:~><:17:~><:18:~><:19:~><:ffffffffffffffff:~>{x
{+>}:8f:{&={+>{~>&=x<:ffffffffffffffff:/#:8f:{{=<:19:x/%
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 28:
=={{header|11l}}==
{{trans|Python}}
<langsyntaxhighlight lang="11l">F average(x)
R sum(x) / Float(x.len)
 
print(average([0, 0, 3, 1, 4, 1, 5, 9, 0, 0]))</langsyntaxhighlight>
{{out}}
<pre>
Line 39:
=={{header|360 Assembly}}==
Compact and functional.
<langsyntaxhighlight lang="360asm">AVGP CSECT
USING AVGP,12
LR 12,15
Line 65:
Z DC CL80' '
U DS CL2
END AVGP</langsyntaxhighlight>
{{out}}
<pre> 5.50</pre>
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.
 
<langsyntaxhighlight lang="6502asm">ArithmeticMean: PHA
TYA
PHA ;push accumulator and Y register onto stack
Line 111:
TAY
PLA
RTS ;return from routine</langsyntaxhighlight>
 
=={{header|8th}}==
<langsyntaxhighlight lang="forth">
: avg \ a -- avg(a)
dup ' n:+ 0 a:reduce
Line 124:
[ 10 ] avg . cr
bye
</syntaxhighlight>
</lang>
Output is:<br>
2.54395<br>
Line 131:
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defun mean-r (xs)
(if (endp xs)
(mv 0 0)
Line 143:
(mv-let (n d)
(mean-r xs)
(/ n d))))</langsyntaxhighlight>
 
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
 
PROC Mean(INT ARRAY a INT count REAL POINTER result)
INT i
REAL x,sum,tmp
 
IntToReal(0,sum)
FOR i=0 TO count-1
DO
IntToReal(a(i),x)
RealAdd(sum,x,tmp)
RealAssign(tmp,sum)
OD
IntToReal(count,tmp)
RealDiv(sum,tmp,result)
RETURN
 
PROC Test(INT ARRAY a INT count)
INT i
REAL result
 
Mean(a,count,result)
Print("mean(")
FOR i=0 TO count-1
DO
PrintI(a(i))
IF i<count-1 THEN
Put(',)
FI
OD
Print(")=")
PrintRE(result)
RETURN
 
PROC Main()
INT ARRAY a1=[1 2 3 4 5 6]
INT ARRAY a2=[1 10 100 1000 10000]
INT ARRAY a3=[9]
 
Put(125) PutE() ;clear screen
Test(a1,6)
Test(a2,5)
Test(a3,1)
Test(a3,0)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Arithmetic_mean.png Screenshot from Atari 8-bit computer]
<pre>
mean(1,2,3,4,5,6)=3.5
mean(1,10,100,1000,10000)=2222.2
mean(9)=9
mean()=0
</pre>
 
=={{header|ActionScript}}==
<langsyntaxhighlight ActionScriptlang="actionscript">function mean(vector:Vector.<Number>):Number
{
var sum:Number = 0;
Line 152 ⟶ 208:
sum += vector[i];
return vector.length == 0 ? 0 : sum / vector.length;
}</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="ada">with Ada.Float_Text_Io; use Ada.Float_Text_Io;
with Ada.Text_IO; use Ada.Text_IO;
 
Line 177 ⟶ 233:
Put(Item => Mean(A (1..0)), Fore => 1, Exp => 0);
New_Line;
end Mean_Main;</langsyntaxhighlight>
Output:
3.83333
Line 184 ⟶ 240:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">real
mean(list l)
{
Line 203 ⟶ 259:
 
0;
}</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 211 ⟶ 267:
{{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.}}
<langsyntaxhighlight lang="algol68">PROC mean = (REF[]REAL p)REAL:
# Calculates the mean of qty REALs beginning at p. #
IF LWB p > UPB p THEN 0.0
Line 223 ⟶ 279:
[6]REAL test := (1.0, 2.0, 5.0, -5.0, 9.5, 3.14159);
print((mean(test),new line))
)</langsyntaxhighlight>
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% procedure to find the mean of the elements of a vector. %
% As the procedure can't find the bounds of the array for itself, %
Line 247 ⟶ 303:
r_format := "A"; r_w := 10; r_d := 2; % set fixed point output %
write( mean( numbers, 1, 5 ) );
end.</langsyntaxhighlight>
 
=={{header|AmigaE}}==
Because of the way Amiga E handles floating point numbers, the passed list/vector must contain
all explicitly floating point values (e.g., you need to write "1.0", not "1")
<langsyntaxhighlight lang="amigae">PROC mean(l:PTR TO LONG)
DEF m, i, ll
ll := ListLen(l)
Line 265 ⟶ 321:
WriteF('mean \s\n',
RealF(s,mean([1.0, 2.0, 3.0, 4.0, 5.0]), 2))
ENDPROC</langsyntaxhighlight>
 
=={{header|AntLang}}==
AntLang has a built-in avg function.
<syntaxhighlight lang AntLang="antlang">avg[list]</langsyntaxhighlight>
 
=={{header|APL}}==
{{works with|APL2}}
<syntaxhighlight lang="apl">
<lang apl> X←3 1 4 1 5 9
X←3 1 4 1 5 9
(+/X)÷⍴X
3.833333333</lang>
</syntaxhighlight>
 
{{works with|Dyalog APL}}
A proper function definition:
<syntaxhighlight lang="apl">
Avg←{(+⌿⍵)÷≢⍵}
Avg 1 2 3 4 5 6
3.5
</syntaxhighlight>
 
Using [[tacit programming]]:
<syntaxhighlight lang="apl">
Avg← +⌿÷≢
Avg 1 2 3 4 5 6
3.5
</syntaxhighlight>
'''N.B.:''' the symbol for [https://aplwiki.com/wiki/Tally Tally (≢)] doesn't display correctly on Chrome-based browsers at the moment.
 
=={{header|AppleScript}}==
Line 282 ⟶ 356:
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.
 
<langsyntaxhighlight lang="applescript">on average(listOfNumbers)
set len to (count listOfNumbers)
if (len is 0) then return missing value
Line 294 ⟶ 368:
end average
 
average({2500, 2700, 2400, 2300, 2550, 2650, 2750, 2450, 2600, 2400})</langsyntaxhighlight>
 
{{output}}
Line 303 ⟶ 377:
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
 
<langsyntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
 
Line 313 ⟶ 387:
end average
 
average({2500, 2700, 2400, 2300, 2550, 2650, 2750, 2450, 2600, 2400})</langsyntaxhighlight>
 
{{output}}
Line 319 ⟶ 393:
 
=={{header|Applesoft BASIC}}==
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">REM COLLECTION IN DATA STATEMENTS, EMPTY DATA IS THE END OF THE COLLECTION
0 READ V$
1 IF LEN(V$) = 0 THEN END
Line 336 ⟶ 410:
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
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight arturolang="rebol">arr: #([1 2 3 4 5 6 7)]
 
print [avgaverage arr]</langsyntaxhighlight>
 
{{out}}
 
<pre>4.0</pre>
 
=={{header|Astro}}==
<langsyntaxhighlight lang="astro">mean([1, 2, 3])
mean(1..10)
mean([])
</syntaxhighlight>
</lang>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">i = 10
Loop, % i {
Random, v, -3.141592, 3.141592
Line 361 ⟶ 435:
sum += v
}
MsgBox, % i ? list "`nmean: " sum/i:0</langsyntaxhighlight>
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">cat mean.awk
#!/usr/local/bin/gawk -f
 
Line 388 ⟶ 462:
print mean(nothing)
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 399 ⟶ 473:
=={{header|Babel}}==
 
<langsyntaxhighlight lang="babel">(3 24 18 427 483 49 14 4294 2 41) dup len <- sum ! -> / itod <<</langsyntaxhighlight>
 
{{Out}}
Line 408 ⟶ 482:
 
Assume the numbers are in an array named "nums".
<langsyntaxhighlight lang="qbasic">mean = 0
sum = 0;
FOR i = LBOUND(nums) TO UBOUND(nums)
Line 419 ⟶ 493:
ELSE
PRINT 0
END IF</langsyntaxhighlight>
 
==={{header|BBC BASIC}}===
Line 425 ⟶ 499:
 
To calculate the mean of an array:
<syntaxhighlight lang="bbc basic">
<lang BBC BASIC>
REM specific functions for the array/vector types
Line 454 ⟶ 528:
DEF FN_Mean_Arithmetic#(n#())
= SUM(n#()) / (DIM(n#(),1)+1)
</syntaxhighlight>
</lang>
[[User:MichaelHutton|Michael Hutton]] 14:02, 29 May 2011 (UTC)
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 NUMERIC ARR(3 TO 8)
110 LET ARR(3)=3:LET ARR(4)=1:LET ARR(5)=4:LET ARR(6)=1:LET ARR(7)=5:LET ARR(8)=9
120 PRINT AM(ARR)
Line 467 ⟶ 541:
170 NEXT
180 LET AM=T/SIZE(A)
190 END DEF</langsyntaxhighlight>
 
=={{header|bc}}==
Uses the current scale for calculating the mean.
<langsyntaxhighlight lang="bc">define m(a[], n) {
auto i, s
 
Line 478 ⟶ 552:
}
return(s / n)
}</langsyntaxhighlight>
 
=={{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>.
<langsyntaxhighlight lang="befunge">&:0\:!v!:-1<
@./\$_\&+\^</langsyntaxhighlight>
 
=={{header|blz}}==
<langsyntaxhighlight lang="blz">
:mean(vec)
vec.fold_left(0, (x, y -> x + y)) / vec.length()
end</langsyntaxhighlight>
 
=={{header|Bracmat}}==
Here are two solutions. The first uses a while loop, the second scans the input by backtracking.
<langsyntaxhighlight lang="bracmat">
(mean1=
sum length n
Line 518 ⟶ 592:
| !sum*!length^-1
);
</syntaxhighlight>
</lang>
To test with a list of all numbers 1 .. 999999:
<langsyntaxhighlight lang="bracmat">
( :?test
& 1000000:?Length
Line 526 ⟶ 600:
& out$mean1$!test
& out$mean2$!test
)</langsyntaxhighlight>
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">mean = { list |
true? list.empty?, 0, { list.reduce(0, :+) / list.length }
}
 
p mean 1.to 10 #Prints 5.5</langsyntaxhighlight>
 
=={{header|Burlesque}}==
 
<langsyntaxhighlight lang="burlesque">
blsq ) {1 2 2.718 3 3.142}av
2.372
blsq ) {}av
NaN
</syntaxhighlight>
</lang>
 
=={{header|BQN}}==
Defines a tacit Avg function which works on any simple numeric list.
 
<syntaxhighlight lang="bqn">Avg ← +´÷≠
 
Avg 1‿2‿3‿4</syntaxhighlight>
<syntaxhighlight lang="text">2.5</syntaxhighlight>
 
[https://mlochbaum.github.io/BQN/try.html#code=QXZnIOKGkCArwrTDt+KJoAoKQXZnIDHigL8y4oC/M+KAvzQ= Try It!]
 
=={{header|C}}==
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>).
 
<langsyntaxhighlight lang="c">#include <stdio.h>
 
double mean(double *v, int len)
Line 570 ⟶ 654:
 
return 0;
}</langsyntaxhighlight>{{out}}<pre>
mean[1, 2, 2.718, 3, 3.142] = 2.372
mean[1, 2, 2.718, 3] = 2.1795
Line 579 ⟶ 663:
</pre>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
 
Line 589 ⟶ 673:
Console.WriteLine(new[] { 1, 2, 3 }.Average());
}
}</langsyntaxhighlight>
 
Alternative version (not using the built-in function):
<langsyntaxhighlight lang="csharp">using System;
 
class Program
Line 620 ⟶ 704:
return d / nums.Length;
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
{{libheader|STL}}
<langsyntaxhighlight lang="cpp">#include <vector>
 
double mean(const std::vector<double>& numbers)
Line 635 ⟶ 719:
sum += *i;
return sum / numbers.size();
}</langsyntaxhighlight>
 
Shorter (and more idiomatic) version:
 
<langsyntaxhighlight lang="cpp">#include <vector>
#include <algorithm>
 
Line 647 ⟶ 731:
return 0;
return std::accumulate(numbers.begin(), numbers.end(), 0.0) / numbers.size();
}</langsyntaxhighlight>
 
Idiomatic version templated on any kind of iterator:
 
<langsyntaxhighlight lang="cpp">#include <iterator>
#include <algorithm>
 
Line 660 ⟶ 744:
return 0;
return std::accumulate(begin, end, 0.0) / std::distance(begin, end);
}</langsyntaxhighlight>
 
=={{header|Chef}}==
 
<langsyntaxhighlight Cheflang="chef">Mean.
 
Chef has no way to detect EOF, so rather than interpreting
Line 694 ⟶ 778:
Pour contents of mixing bowl into baking dish.
 
Serves 1.</langsyntaxhighlight>
 
=={{header|Clojure}}==
 
Returns a [http://clojure.org/data_structures ratio]:
<langsyntaxhighlight lang="lisp">(defn mean [sq]
(if (empty? sq)
0
(/ (reduce + sq) (count sq))))</langsyntaxhighlight>
 
Returns a float:
<langsyntaxhighlight lang="lisp">(defn mean [sq]
(if (empty? sq)
0
(float (/ (reduce + sq) (count sq)))))</langsyntaxhighlight>
 
=={{header|COBOL}}==
Intrinsic function:
<langsyntaxhighlight lang="cobol">FUNCTION MEAN(some-table (ALL))</langsyntaxhighlight>
 
Sample implementation:
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. find-mean.
 
Line 742 ⟶ 826:
 
GOBACK
.</langsyntaxhighlight>
 
=={{header|Cobra}}==
 
<langsyntaxhighlight lang="cobra">
class Rosetta
def mean(ns as List<of number>) as number
Line 760 ⟶ 844:
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])]"
</syntaxhighlight>
</lang>
 
Output:
Line 769 ⟶ 853:
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
mean = (array) ->
return 0 if array.length is 0
Line 777 ⟶ 861:
alert mean [1]
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
'''With Reduce'''
 
<langsyntaxhighlight lang="lisp">(defun mean (&rest sequence)
(if (nullwhen sequence)
(/ (reduce #'+ sequence) (length sequence))))</syntaxhighlight>
nil
(/ (reduce #'+ sequence) (length sequence))))</lang>
 
'''With Loop'''
<langsyntaxhighlight lang="lisp">(defun mean (list)
(unless (nullwhen list)
(/ (loop for i in list sum i)
(length list))))</langsyntaxhighlight>
 
=={{header|Craft Basic}}==
<syntaxhighlight lang="basic">dim a[3, 1, 4, 1, 5, 9]
 
arraysize s, a
 
for i = 0 to s - 1
 
let t = t + a[i]
 
next i
 
print t / s</syntaxhighlight>
{{out| Output}}<pre>3.83</pre>
 
=={{header|Crystal}}==
<langsyntaxhighlight lang="ruby"># Crystal will return NaN if an empty array is passed
def mean(arr) : Float64
arr.sum / arr.size.to_f
end</langsyntaxhighlight>
 
=={{header|D}}==
===Imperative Version===
<langsyntaxhighlight lang="d">real mean(Range)(Range r) pure nothrow @nogc {
real sum = 0.0;
int count;
Line 823 ⟶ 920:
data = [3, 1, 4, 1, 5, 9];
writeln("Mean: ", data.mean);
}</langsyntaxhighlight>
{{out}}
<pre>mean: 0
mean: 3.83333</pre>
===More Functional Version===
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range;
 
real mean(Range)(Range r) pure nothrow @nogc {
Line 837 ⟶ 934:
writeln("Mean: ", (int[]).init.mean);
writeln("Mean: ", [3, 1, 4, 1, 5, 9].mean);
}</langsyntaxhighlight>
{{out}}
<pre>Mean: 0
Line 844 ⟶ 941:
===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):
<langsyntaxhighlight lang="d">import std.stdio, std.conv, std.algorithm, std.math, std.traits;
 
CommonType!(T, real) mean(T)(T[] n ...) if (isNumeric!T) {
Line 857 ⟶ 954:
writefln("%8.5f", mean( 0, 3, 1, 4, 1, 5, 9, 0));
writefln("%8.5f", mean([-1e20, 3, 1, 4, 1, 5, 9, 1e20]));
}</langsyntaxhighlight>
{{out}}
<pre> 0.00000
Line 864 ⟶ 961:
 
=={{header|Dart}}==
<langsyntaxhighlight lang="d">num mean(List<num> l) => l.reduce((num p, num n) => p + n) / l.length;
 
void main(){
print(mean([1,2,3,4,5,6,7]));
}</langsyntaxhighlight>
{{out}}
<pre>4.0</pre>
Line 875 ⟶ 972:
This is not a translation of the bc solution. Array handling would add some complexity. This one-liner is similar to the K solution.
 
<langsyntaxhighlight lang="dc">1 2 3 5 7 zsn1k[+z1<+]ds+xln/p
3.6</langsyntaxhighlight>
 
An expanded example, identifying an empty sample set, could be created as a file, e.g., amean.cd:
 
<langsyntaxhighlight lang="dc">[[Nada Mean: ]Ppq]sq
zd0=qsn [stack length = n]sz
1k [precision can be altered]sz
[+z1<+]ds+x[Sum: ]Pp
ln/[Mean: ]Pp
[Sample size: ]Plnp</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="dc">$ dc sample.dc amean.cd
Sum: 18
Mean: 3.6
Sample size: 5
$</langsyntaxhighlight>
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program AveragesArithmeticMean;
 
{$APPTYPE CONSOLE}
Line 917 ⟶ 1,014:
Writeln(Mean(TDoubleDynArray.Create()));
Writeln(Mean(TDoubleDynArray.Create(1,2,3,4,5)));
end.</langsyntaxhighlight>
 
=={{header|Dyalect}}==
 
<langsyntaxhighlight lang="dyalect">func avg(args...) {
var acc = .0
var len = 0
Line 931 ⟶ 1,028:
}
 
avg(1, 2, 3, 4, 5, 6)</langsyntaxhighlight>
 
=={{header|E}}==
Line 937 ⟶ 1,034:
Slightly generalized to support any object that allows iteration.
 
<langsyntaxhighlight lang="e">def meanOrZero(numbers) {
var count := 0
var sum := 0
Line 945 ⟶ 1,042:
}
return sum / 1.max(count)
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="text">
<lang>func mean . f[] r .
proc mean . f[] r .
for i range len f[]
for si += 1 to len f[i]
s += f[i]
.
.
r = s / len f[]
r = s / len f[]
.
f[] = [ 1 2 3 4 5 6 7 8 ]
call mean f[] r
print r</lang>
</syntaxhighlight>
 
=={{header|EchoLisp}}==
'''(mean values)''' is included in math.lib. values may be a list, vector, sequence, or any kind of procrastinator.
<langsyntaxhighlight lang="scheme">
(lib 'math)
(mean '(1 2 3 4)) ;; mean of a list
Line 982 ⟶ 1,081:
😁 warning: mean : zero-divide : empty-sequence
→ 0
</syntaxhighlight>
</lang>
 
=={{header|ECL}}==
<langsyntaxhighlight lang="ecl">
AveVal(SET OF INTEGER s) := AVE(s);
Line 992 ⟶ 1,091:
SetVals := [14,9,16,20,91];
AveVal(SetVals) //returns 30.0 ;
</syntaxhighlight>
</lang>
 
=={{header|EDSAC order code}}==
Extends the RC task by finding the arithmetic mean for each of several data sets. Each data set is preceded by the number of data. A count of 0 is not an error but signals that there are no more data sets.
 
The program needs to avoid the possibility of arithmetic overflow, as pointed out in the F# solution. The moving average used there is not well-suited to EDSAC, on which division had to be done by calling a subroutine. After reading the number of data N, and leaving the trivial case N = 1 for separate treatment, the program first calculates 1/N, then multiplies each value by 1/N before adding it into the result.
<syntaxhighlight lang="edsac">
[Averages/Arithmetic mean - Rosetta Code]
 
[EDSAC program (Initial Orders 2) to find and print the average of
a sequence of 35-bit fractional values.
Values are read from tape, preceded by an integer count.]
 
[Library subroutine M3, runs at load time and is then overwritten.
Prints header; here, last character sets teleprinter to figures.]
PF GK IF AF RD LF UF OF E@ A6F G@ E8F EZ PF
*!!!!!COUNT!!!!!!AVERAGE@&#.. [PZ]
 
[Main routine: must be at even address]
T214K GK
[0] PF PF [average value]
[2] PF PF [reciprocal of data count]
[4] PF [data count]
[5] PD [17-bit constant 1; also serves as '0' for printing]
[6] @F [carriage return]
[7] &F [line feed]
[8] !F [space]
[9] MF [dot (in figures mode)]
[10] K4096F [teleprinter null]
[Entry and outer loop]
[11] A11@
G56F [call library subroutine R4, sets 0D := data count N]
SD E64@ [exit if N = 0]
T4F [clear acc]
AF T4@ [load and save N (assumed < 2^16)]
[18] A18@ G156F [print N (clears acc)]
TD [clear whole of 0D, including sandwich bit]
T4D [same for 4D]
A4@ S2F [acc := N - 2]
G66@ [jump to special action if N = 1]
A2F [restore N after test]
T5F [store N in 4D high word]
A5@ T1F [store 1 in 0D high word]
[29] A29@ G120F [call library subroutine D6, sets 0D := 0D/4D]
AD T2#@ [load and save 1/N]
T#@ [clear average]
S4@ [load -N]
[Inner loop]
[35] T4@ [update negative loop counter]
[36] A36@ G78F [read next datum to 0D (clears acc)]
H2#@ [mult reg := 1/N]
VD [acc := datum/N]
A#@ T#@ [add into average]
A4@ A5@ [increment negative loop counter]
G35@ [loop until counter = 0]
[45] O8@ O8@ [print 2 spaces]
[Print the average value.
NB: Library subroutine P1 requires non-negative input and prints only the
digits after the decimal point. Formatting has to be done by the caller.]
[47] A#@ [load average (order also serves as minus sign)]
G52@ [jump if average < 0]
TD [pass average to subroutine P1]
O65@ [print plus sign (or could be space)]
E56@ [join common code]
[52] TD [average < 0; clear acc]
S#@ TD [pass abs(average) to subroutine P1]
O47@ [print minus sign]
[56] O5@ O9@ [common code: print '0.']
[58] A58@ G192F [call P1 to print abs(average)]
P8F [8 decimal places]
O6@ O7@ [print CR, LF]
E11@ [loop back always (because acc = 0)]
[Jump to here if data count = 0, means end of data]
[64] O10@ [print null to flush teleprinter buffer]
[65] ZF [halt the machine (order also serves as plus sign)]
[Jump to here if data count = 1]
[66] TF [clear acc]
[67] A67@ G78F [read datum to 0D]
AD T#@ [average := datum]
E45@ [jump to print the average]
 
[The following puts the entry address into location 50,
so that it can be accessed via the X parameter (see end of program).
This is done in case the data is input from a separate tape.]
T50K P11@ T11Z
 
[Library subroutine R4.
Input of one signed integer, returned in 0D.]
T56K
GKA3FT21@T4DH6@E11@P5DJFT6FVDL4FA4DTDI4FA4FS5@G7@S5@G20@SDTDT6FEF
 
[Library subroutine R3.
Input of one long signed decimal fraction, returned in 0D.]
T78K
GKT45KP26@TZA3FTHTDT4DA6HT9@H1HS4HT6FIFAFS4HE7HT7FV4DL8FADT4DA6FA5HG8@
H2#HN4DLDYFTDT28#ZPFT27ZTFP610D@524DP5DPDIFS4HG37@S4DT4DT7FA1HT9@E18@
 
[Library subroutine D6 - Division, accurate, fast.
36 locations, workspace 6D and 8D.
0D := 0D/4D, where 4D <> 0, -1.]
T120K
GKA3FT34@S4DE13@T4DSDTDE2@T4DADLDTDA4DLDE8@RDU4DLDA35@
T6DE25@U8DN8DA6DT6DH6DS6DN4DA4DYFG21@SDVDTDEFW1526D
 
[Library subroutine P7: print strictly positive integer in 0D.]
T156K
GKA3FT26@H28#@NDYFLDT4DS27@TFH8@S8@T1FV4DAFG31@SFLDUFOFFFSF
L4FT4DA1FA27@G11@T28#ZPFT27ZP1024FP610D@524D!FO30@SFL8FE22@
 
[Library subroutine P1: print non-negative fraction in 0D, without '0.']
T192K
GKA18@U17@S20@T5@H19@PFT5@VDUFOFFFSFL4FTDA5@A2FG6@EFU3FJFM1F
 
[==========================================================================
On the original EDSAC, the following (without the whitespace and comments)
might have been input on a separate tape.]
 
E25K TX GK
EZ [define entry point]
PF [acc = 0 on entry]
 
[Counts and data values to be read by library subroutines R3 and R4 respectively.
Note (1) Sign comes *after* value (2) In the data, leading '0.' is omitted.]
7+ 1-2-3-4-5+2-3-
1+ 987654321+
9+ 01+04+09+16+25+36+49+64+81+
9+ 01-04+09-16+25-36+49-64+81-
[Daily minimum temperature (unit = 10 deg. C), Cambridge, UK, January 2000]
31+ 34+14+49+00+04+48+05+48+23-35-07-75+19+03+
26+27+17-06-52+22-17+18+15+03-33-11-04-01-44+89+95+
0+
</syntaxhighlight>
{{out}}
<pre>
COUNT AVERAGE
7 -0.14285714
1 +0.98765432
9 +0.31666666
9 -0.05000000
31 +0.16774193
</pre>
 
=={{header|Elena}}==
ELENA 56.0x:
<langsyntaxhighlight lang="elena">import extensions;
 
extension op
Line 1,009 ⟶ 1,248:
while (enumerator.next())
{
sum += *enumerator.get();
count += 1;
};
Line 1,023 ⟶ 1,262:
"Arithmetic mean of {",array.asEnumerable(),"} is ",
array.average()).readChar()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,030 ⟶ 1,269:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Average do
def mean(list), do: Enum.sum(list) / length(list)
end</langsyntaxhighlight>
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang ="lisp"> (defun mean (lst)
(/ (float (apply '+ lst)) (length lst)))
(mean '(1 2 3 4))</langsyntaxhighlight>
 
{{libheader|Calc}}
Calculate mean by Emacs Lisp and built-in Emacs Calc
 
<langsyntaxhighlight lang="lisp">(setqlet ((x '[(1 2 3 4])))
(string-to-number (calc-eval (format "vmean(%s$1)" nil (append '(vec) x)))</langsyntaxhighlight>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
fun mean = real by some real values
real sum
int count
for each real value in values
sum += value
++count
end
return when(count == 0, 0.0, sum / count)
end
writeLine(mean())
writeLine(mean(3,1,4,1,5,9))
</syntaxhighlight>
{{out}}
<pre>
0.0
3.8333333333333333333333333333
</pre>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">mean([]) -> 0;
mean(L) -> lists:sum(L)/erlang:length(L).</langsyntaxhighlight>
 
=={{header|Euphoria}}==
<langsyntaxhighlight Euphorialang="euphoria">function mean(sequence s)
atom sum
if length(s) = 0 then
Line 1,064 ⟶ 1,323:
sequence test
test = {1.0, 2.0, 5.0, -5.0, 9.5, 3.14159}
? mean(test)</langsyntaxhighlight>
 
=={{header|Excel}}==
Assuming the values are entered in the A column, type into any cell which will not be part of the list:
 
<langsyntaxhighlight lang="excel">=AVERAGE(A1:A10)</langsyntaxhighlight>
 
Assuming 10 values will be entered, alternatively, you can just type:
 
<langsyntaxhighlight lang="excel">=AVERAGE(</langsyntaxhighlight>
 
and then select the start and end cells, not necessarily in the same row or column.
Line 1,094 ⟶ 1,353:
=={{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.
<langsyntaxhighlight lang="fsharp">let avg (a:float) (v:float) n =
a + (1. / ((float n) + 1.)) * (v - a)
 
let mean_series list =
let a, _ = List.fold_left (fun (a, n) h -> avg a (float h) n, n + 1) (0., 0) list in
a</langsyntaxhighlight>
 
Checking this:
<langsyntaxhighlight lang="fsharp"> > mean_series [1; 8; 2; 8; 1; 7; 1; 8; 2; 7; 3; 6; 1; 8; 100] ;;
val it : float = 10.86666667
> mean_series [] ;;
val it : float = 0.0</langsyntaxhighlight>
 
We can also make do with the built-in ''List.average'' function:
<langsyntaxhighlight lang="fsharp">List.average [4;1;7;5;8;4;5;2;1;5;2;5]</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: math math.statistics ;
 
: arithmetic-mean ( seq -- n )
[ 0 ] [ mean ] if-empty ;</langsyntaxhighlight>
 
Tests:
 
<langsyntaxhighlight lang="factor">( scratchpad ) { 2 3 5 } arithmetic-mean >float
3.333333333333333</langsyntaxhighlight>
 
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 1,142 ⟶ 1,401:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Fish}}==
<langsyntaxhighlight Fishlang="fish">!vl0=?vl1=?vl&!
v< +<>0n; >n;
>l1)?^&,n;</langsyntaxhighlight>
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>
Line 1,154 ⟶ 1,413:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: fmean ( addr n -- f )
0e
dup 0= if 2drop exit then
Line 1,163 ⟶ 1,422:
 
create test 3e f, 1e f, 4e f, 1e f, 5e f, 9e f,
test 6 fmean f. \ 3.83333333333333</langsyntaxhighlight>
 
=={{header|Fortran}}==
In ISO Fortran 90 or later, use the SUM intrinsic, the SIZE intrinsic and the MAX intrinsic (to avoid divide by zero):
<langsyntaxhighlight lang="fortran">real, target, dimension(100) :: a = (/ (i, i=1, 100) /)
real, dimension(5,20) :: b = reshape( a, (/ 5,20 /) )
real, pointer, dimension(:) :: p => a(2:1) ! pointer to zero-length array
Line 1,186 ⟶ 1,445:
! dividing by the length of the row, which is the number of columns (SIZE of dimension 2)
colmeans = sum(b,2)/max(size(b,1),1) ! SUM elements in each column (dimension 2)
! dividing by the length of the column, which is the number of rows (SIZE of dimension 1)</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">
' FB 1.05.0 Win64
 
Line 1,232 ⟶ 1,491:
Print "Press any key to quit the program"
Sleep
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,254 ⟶ 1,513:
=={{header|Frink}}==
The following works on arrays or sets. If the collection is empty, this returns the special value <CODE>undef</CODE>.
<langsyntaxhighlight lang="frink">
mean[x] := length[x] > 0 ? sum[x] / length[x] : undef
</syntaxhighlight>
</lang>
 
 
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn MeanAverageOfNumberArray( numberArr as CFArrayRef ) as CFStringRef
CFStringRef result = NULL
if len(numberArr) == 0 then result = @"Mean undefined for empty array." : exit fn
result = fn StringWithFormat( @"Mean average of %d numbers: %@", len(numberArr), fn ObjectValueForKeyPath( numberArr, @"@avg.self" ) )
end fn = result
 
CFArrayRef numberArray
numberArray = @[@1, @2, @3, @4, @5, @6, @7, @8, @9, @10]
print fn MeanAverageOfNumberArray( numberArray )
numberArray = @[@3, @1, @4, @1, @5, @9]
print fn MeanAverageOfNumberArray( numberArray )
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Mean average of 10 numbers: 5.5
Man average of 6 numbers: 3.83333333333333333333333333333333333333
</pre>
 
 
</pre>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">Mean := function(v)
local n;
n := Length(v);
Line 1,270 ⟶ 1,556:
 
Mean([3, 1, 4, 1, 5, 9]);
# 23/6</langsyntaxhighlight>
 
=={{header|GEORGE}}==
<langsyntaxhighlight GEORGElang="george">R (n) P ;
0
1, n rep (i)
Line 1,279 ⟶ 1,565:
]
n div
P</langsyntaxhighlight>
Output:
<pre>
Line 1,299 ⟶ 1,585:
This works for arrays of integers.
 
<syntaxhighlight lang="text">
DIM a%(10)
FOR i%=0 TO 10
Line 1,323 ⟶ 1,609:
RETURN sum/size%
ENDFUNC
</syntaxhighlight>
</lang>
 
=={{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.
 
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,392 ⟶ 1,678:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,418 ⟶ 1,704:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def avg = { list -> list == [] ? 0 : list.sum() / list.size() }</langsyntaxhighlight>
 
Test Program:
<langsyntaxhighlight lang="groovy">println avg(0..9)
println avg([2,2,2,4,2])
println avg ([])</langsyntaxhighlight>
 
Output:
Line 1,432 ⟶ 1,718:
=={{header|Haskell}}==
This function works if the element type is an instance of Fractional:
<langsyntaxhighlight lang="haskell">mean :: (Fractional a) => [a] -> a
mean [] = 0
mean xs = sum xs / Data.List.genericLength xs</langsyntaxhighlight>
 
But some types, e.g. integers, are not Fractional; the following function works for all Real types:
<langsyntaxhighlight lang="haskell">meanReals :: (Real a, Fractional b) => [a] -> b
meanReals = mean . map realToFrac</langsyntaxhighlight>
 
If you want to avoid keeping the list in memory and traversing it twice:
 
<langsyntaxhighlight lang="haskell">{-# LANGUAGE BangPatterns #-}
 
import Data.List (foldl') --'
Line 1,460 ⟶ 1,746:
 
main :: IO ()
main = print $ mean [1 .. 100]</langsyntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">REAL :: vec(100) ! no zero-length arrays in HicEst
 
vec = $ - 1/2 ! 0.5 ... 99.5
mean = SUM(vec) / LEN(vec) ! 50
END </langsyntaxhighlight>
 
=={{header|Hy}}==
Returns <tt>None</tt> if the input is of length zero.
<langsyntaxhighlight lang="clojure">(defn arithmetic-mean [xs]
(if xs
(/ (sum xs) (len xs))))</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight lang="icon">procedure main(args)
every (s := 0) +:= !args
write((real(s)/(0 ~= *args)) | 0)
end</langsyntaxhighlight>
 
Sample outputs:
Line 1,492 ⟶ 1,778:
If truly only the mean is wanted, one could use
 
<langsyntaxhighlight lang="idl">x = [3,1,4,1,5,9]
print,mean(x)</langsyntaxhighlight>
 
But <tt>mean()</tt> is just a thin wrapper returning the zeroth element of <tt>moment()</tt> :
 
<langsyntaxhighlight lang="idl">print,moment(x)
; ==>
3.83333 8.96667 0.580037 -1.25081</langsyntaxhighlight>
 
which are mean, variance, skewness and kurtosis.
Line 1,507 ⟶ 1,793:
=={{header|J}}==
 
<langsyntaxhighlight lang="j">mean=: +/ % #</langsyntaxhighlight>
 
That is, sum divided by the number of items. The verb also works on higher-ranked arrays. For example:
 
<langsyntaxhighlight lang="j"> mean 3 1 4 1 5 9
3.83333
mean $0 NB. $0 is a zero-length vector
Line 1,517 ⟶ 1,803:
x=: 20 4 ?@$ 0 NB. a 20-by-4 table of random (0,1) numbers
mean x
0.58243 0.402948 0.477066 0.511155</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="j">mean1=: 3 : 0
z=. 0
for_i. i.#y do. z=. z+i{y end.
Line 1,531 ⟶ 1,817:
0
mean1 x
0.58243 0.402948 0.477066 0.511155</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
 
<langsyntaxhighlight lang="java5">public static double avg(double... arr) {
double sum = 0.0;
for (double x : arr) {
Line 1,542 ⟶ 1,828:
}
return sum / arr.length;
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 1,548 ⟶ 1,834:
===ES5===
 
<langsyntaxhighlight lang="javascript">function mean(array)
{
var sum = 0, i;
Line 1,559 ⟶ 1,845:
 
alert( mean( [1,2,3,4,5] ) ); // 3
alert( mean( [] ) ); // 0</langsyntaxhighlight>
 
Using the native function `.forEach()`:
<langsyntaxhighlight lang="javascript">function mean(array) {
var sum = 0;
array.forEach(function(value){
Line 1,570 ⟶ 1,856:
}
 
alert( mean( [1,2,3,4,5] ) ); // 3</langsyntaxhighlight>
 
Using the native function `.reduce()`:
<langsyntaxhighlight lang="javascript">function mean(array) {
return !array.length ? 0
: array.reduce(function(pre, cur, i) {
Line 1,582 ⟶ 1,868:
alert( mean( [1,2,3,4,5] ) ); // 3
alert( mean( [] ) ); // 0
</syntaxhighlight>
</lang>
 
Extending the `Array` prototype:
<langsyntaxhighlight lang="javascript">Array.prototype.mean = function() {
return !this.length ? 0
: this.reduce(function(pre, cur, i) {
Line 1,594 ⟶ 1,880:
alert( [1,2,3,4,5].mean() ); // 3
alert( [].mean() ); // 0
</syntaxhighlight>
</lang>
 
 
{{libheader|Functional}}
<langsyntaxhighlight lang="javascript">function mean(a)
{
return a.length ? Functional.reduce('+', 0, a) / a.length : 0;
}</langsyntaxhighlight>
 
 
===ES6===
 
<langsyntaxhighlight JavaScriptlang="javascript">(sample => {
 
// mean :: [Num] => (Num | NaN)
Line 1,619 ⟶ 1,905:
return mean(sample);
 
})([1, 2, 3, 4, 5, 6, 7, 8, 9]);</langsyntaxhighlight>
 
{{Out}}
<syntaxhighlight lang="javascript">5</syntaxhighlight>
<lang JavaScript>5</lang>
 
=={{header|Joy}}==
<syntaxhighlight lang="joy">DEFINE avg == dup 0. [+] fold swap size 1 max /.</syntaxhighlight>
 
=={{header|jq}}==
The mean of an array of numbers can be computed by simply writing
<syntaxhighlight lang ="jq">add/length</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang="jq">def mean: if length == 0 then null
else add/length
end;</langsyntaxhighlight>
 
=={{header|Julia}}==
Julia's built-in mean function accepts AbstractArrays (vector, matrix, etc.)
<langsyntaxhighlight lang="julia">julia> using Statistics; mean([1,2,3])
2.0
julia> mean(1:10)
5.5
julia> mean([])
ERROR: mean of empty collection undefined: []</langsyntaxhighlight>
 
=={{header|K}}==
<langsyntaxhighlight lang="k"> mean: {(+/x)%#x}
mean 1 2 3 5 7
3.6
mean@!0 / empty array
0.0</langsyntaxhighlight>
 
=={{header|Kotlin}}==
Kotlin has builtin functions for some collection types.
Example:
<langsyntaxhighlight 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)
println("average = %f".format(nums.average()))
}</langsyntaxhighlight>
 
=={{header|KQL}}==
<langsyntaxhighlight lang="kql">
let dataset = datatable(values:real)[
1, 1.5, 3, 5, 6.5];
 
dataset|summarize avg(values)
</syntaxhighlight>
</lang>
 
Output:
Line 1,676 ⟶ 1,965:
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
{def mean
{lambda {:s}
Line 1,685 ⟶ 1,974:
{mean {S.serie 0 1000}}
-> 500
</syntaxhighlight>
</lang>
 
=={{header|langur}}==
Line 1,692 ⟶ 1,981:
We could use fold() to write a function that takes an array and calculates the mean.
 
<syntaxhighlight lang="langur">val .mean = fn(.x) { fold(fn{+}, .x) / len(.x) }
{{works with|langur|0.6.6}}
<lang langur>val .mean = f(.x) fold(f{+}, .x) / len(.x)
 
writeln " custom: ", .mean([7, 3, 12])
writeln "built-in: ", mean([7, 3, 12])</langsyntaxhighlight>
 
{{out}}
Line 1,703 ⟶ 1,991:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define average(a::array) => {
not #a->size ? return 0
local(x = 0.0)
Line 1,710 ⟶ 1,998:
}
 
average(array(1,2,5,17,7.4)) //6.48</langsyntaxhighlight>
 
=={{header|LFE}}==
Line 1,716 ⟶ 2,004:
=== 1-Arity ===
 
<langsyntaxhighlight lang="lisp">
(defun mean (data)
(/ (lists:sum data)
(length data)))
</syntaxhighlight>
</lang>
 
Usage:
<langsyntaxhighlight lang="lisp">> (mean '(1 1))
1.0
> (mean '(1 2))
Line 1,730 ⟶ 2,018:
6.0
> (mean '(6 12 18 24 30 36 42 48 54 60 66 72 78))
42.0</langsyntaxhighlight>
 
=== n-Arity ===
Line 1,736 ⟶ 2,024:
Functions in LFE (and Erlang) have set arity, but macros can be used to provide the same use as n-arity functions:
 
<langsyntaxhighlight lang="lisp">(defmacro mean args
`(/ (lists:sum ,args)
,(length args)))</langsyntaxhighlight>
 
Usage:
 
<langsyntaxhighlight lang="lisp">> (mean 42)
42.0
> (mean 18 66)
42.0
> (mean 6 12 18 24 30 36 42 48 54 60 66 72 78)
42.0</langsyntaxhighlight>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">total=17
dim nums(total)
for i = 1 to total
Line 1,761 ⟶ 2,049:
if total=0 then mean=0 else mean=sum/total
print "Arithmetic mean: ";mean
</langsyntaxhighlight>
 
=={{header|Limbo}}==
<langsyntaxhighlight Limbolang="limbo">implement Command;
 
include "sys.m";
Line 1,787 ⟶ 2,075:
n += a[i];
return n / (real len a);
}</langsyntaxhighlight>
 
=={{header|Lingo}}==
<langsyntaxhighlight Lingolang="lingo">-- v can be (2D) point, (3D) vector or list of integers/floats
on mean (v)
case ilk(v) of
Line 1,803 ⟶ 2,091:
end repeat
return float(sum)/cnt
end</langsyntaxhighlight>
 
<langsyntaxhighlight Lingolang="lingo">put mean(point(1, 2.5))
-- 1.7500
put mean(vector(1.2, 4.7, 5.6))
-- 3.8333
put mean([6,12,18,24,30,36,42,48,54,60,66,72,78])
-- 42.0000</langsyntaxhighlight>
 
=={{header|LiveCode}}==
Livecode provides arithmeticMean (avg, average) built-in.
<langsyntaxhighlight LiveCodelang="livecode">average(1,2,3,4,5) -- 3
average(empty) -- 0</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to average :l
if empty? :l [output 0]
output quotient apply "sum :l count :l
end
print average [1 2 3 4] ; 2.5</langsyntaxhighlight>
 
=={{header|Logtalk}}==
Logtalk's standard library provides an arithmetic average predicate but we ignore it here. Representing a vector using a list:
<langsyntaxhighlight lang="logtalk">
:- object(averages).
 
Line 1,844 ⟶ 2,132:
 
:- end_object.
</syntaxhighlight>
</lang>
Sample output:
<langsyntaxhighlight lang="text">
| ?- averages::arithmetic([1,2,3,4,5,6,7,8,9,10], Mean).
Mean = 5.5
yes
</syntaxhighlight>
</lang>
 
=={{header|LSL}}==
<langsyntaxhighlight LSLlang="lsl">integer MAX_ELEMENTS = 10;
integer MAX_VALUE = 100;
default {
Line 1,874 ⟶ 2,162:
llOwnerSay(" Sum Squares: "+(string)llListStatistics(LIST_STAT_SUM_SQUARES, lst));
}
}</langsyntaxhighlight>
Output:
<pre>
Line 1,891 ⟶ 2,179:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function mean (numlist)
if type(numlist) ~= 'table' then return numlist end
num = 0
Line 1,898 ⟶ 2,186:
end
 
print (mean({3,1,4,1,5,9}))</langsyntaxhighlight>
 
=={{header|Lucid}}==
 
<langsyntaxhighlight lang="lucid">avg(x)
where
sum = first(x) fby sum + next(x);
n = 1 fby n + 1;
avg = sum / n;
end</langsyntaxhighlight>
 
=={{header|M4}}==
Line 1,915 ⟶ 2,203:
directly, but it is a little bit clearer to keep them separated.
 
<langsyntaxhighlight 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(`mean', `rmean(`$#', $@)')dnl
define(`rmean', `ifelse(`$3', `', `fmean($1,$2)',dnl
`rmean($1, eval($2+$3), shift(shift(shift($@))))')')dnl</langsyntaxhighlight>
<langsyntaxhighlight lang="m4">mean(0,100,200,300,400,500,600,700,800,900,1000)</langsyntaxhighlight>
 
=={{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.
<syntaxhighlight lang="maple">
<lang Maple>
mean := proc( a :: indexable )
local i;
Normalizer( add( i, i in a ) / numelems( a ) )
end proc:
</syntaxhighlight>
</lang>
For example:
<syntaxhighlight lang="maple">
<lang Maple>
> mean( { 1/2, 2/3, 3/4, 4/5, 5/6 } ); # set
71
Line 1,953 ⟶ 2,241:
> mean([]); # empty argument causes an exception to be raised.
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.
<langsyntaxhighlight Maplelang="maple">mean := () -> Normalizer( `+`( args ) / nargs ):</langsyntaxhighlight>
This can be called as in the following examples.
<syntaxhighlight lang="maple">
<lang Maple>
> mean( 1, 2, 3, 4, 5 );
3
Line 1,968 ⟶ 2,256:
> mean(); # again, an exception is raised
Error, (in mean) numeric exception: division by zero
</syntaxhighlight>
</lang>
If desired, we can add argument type-checking as follows.
<langsyntaxhighlight Maplelang="maple">mean := ( s :: seq(algebraic) ) -> Normalizer( `+`( args ) / nargs ):</langsyntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Modify the built-in Mean function to give 0 for empty vectors (lists in Mathematica):
<langsyntaxhighlight lang="mathematica">Unprotect[Mean];
Mean[{}] := 0</langsyntaxhighlight>
Examples:
<langsyntaxhighlight lang="mathematica">Mean[{3,4,5}]
Mean[{3.2,4.5,5.9}]
Mean[{-4, 1.233}]
Mean[{}]
Mean[{1/2,1/3,1/4,1/5}]
Mean[{a,c,Pi,-3,a}]</langsyntaxhighlight>
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):
<langsyntaxhighlight lang="mathematica">4
4.53333
-1.3835
0
77/240
1/5 (-3+2 a+c+Pi)</langsyntaxhighlight>
 
=={{header|Mathprog}}==
Line 2,001 ⟶ 2,289:
To make it more interesting I find the Arithmectic Mean of more than a million Integers.
 
<syntaxhighlight lang="text">
/*Arithmetic Mean of a large number of Integers
- or - solve a very large constraint matrix
Line 2,026 ⟶ 2,314:
 
end;
</syntaxhighlight>
</lang>
 
When run this produces:
 
<syntaxhighlight lang="text">
GLPSOL: GLPK LP/MIP Solver, v4.47
Parameter(s) specified in the command line:
Line 2,053 ⟶ 2,341:
The arithmetic mean of the integers from 1 to 1048575 is 524288.000000
Model has been successfully processed
</syntaxhighlight>
</lang>
 
=={{header|MATLAB}}==
<langsyntaxhighlight Matlablang="matlab">function meanValue = findmean(setOfValues)
meanValue = mean(setOfValues);
end</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">load("descriptive");
mean([2, 7, 11, 17]);</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">fn mean data =
(
total = 0
Line 2,075 ⟶ 2,363:
)
 
print (mean #(3, 1, 4, 1, 5, 9))</langsyntaxhighlight>
 
=={{header|Mercury}}==
<langsyntaxhighlight lang="mercury">:- module arithmetic_mean.
:- interface.
 
Line 2,097 ⟶ 2,385:
mean(Ns @ [_ | _]) = foldl((+), Ns, 0.0) / float(length(Ns)).
 
:- end_module arithmetic_mean.</langsyntaxhighlight>
 
Alternatively, we could use inst subtyping to ensure we get a compilation error if the
mean function is called with an empty list.
 
<langsyntaxhighlight lang="mercury">:- func mean(list(float)::in(non_empty_list)) = (float::out).
 
mean(Ns) = foldl((+), Ns, 0.0) / float(length(Ns)).</langsyntaxhighlight>
 
=={{header|min}}==
Returns <code>nan</code> for an empty quotation.
{{works with|min|0.1937.30}}
<syntaxhighlight lang ="min">(((02 (+)3 reduce5) (sizeavg puts!</)) cleave) :meansyntaxhighlight>
(2 3 5) mean print</lang>
{{out}}
<pre>3.333333333333333</pre>
<pre>
3.333333333333334
</pre>
 
=={{header|MiniScript}}==
 
<langsyntaxhighlight MiniScriptlang="miniscript">arr = [ 1, 3, 7, 8, 9, 1 ]
 
avg = function(arr)
Line 2,128 ⟶ 2,413:
end function
 
print avg(arr)</langsyntaxhighlight>
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">0 П0 П1 С/П ИП0 ИП1 * + ИП1 1
+ П1 / П0 БП 03</langsyntaxhighlight>
 
''Instruction:'' В/О С/П Number С/П Number ...
Line 2,139 ⟶ 2,424:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">PROCEDURE Avg;
 
VAR avg : REAL;
Line 2,148 ⟶ 2,433:
InOut.WriteReal (avg, 8, 2);
InOut.WriteLn
END Avg;</langsyntaxhighlight>
OR
<langsyntaxhighlight lang="modula2">PROCEDURE Average (Data : ARRAY OF REAL; Samples : CARDINAL) : REAL;
 
(* Calculate the average over 'Samples' values, stored in array 'Data'. *)
Line 2,163 ⟶ 2,448:
END;
RETURN sum / FLOAT(Samples)
END Average;</langsyntaxhighlight>
 
=={{header|MUMPS}}==
<langsyntaxhighlight MUMPSlang="mumps">MEAN(X)
;X is assumed to be a list of numbers separated by "^"
QUIT:'$DATA(X) "No data"
Line 2,173 ⟶ 2,458:
SET S=0,I=1
FOR QUIT:I>$L(X,"^") SET S=S+$P(X,"^",I),I=I+1
QUIT (S/$L(X,"^"))</langsyntaxhighlight>
<pre>USER>W $$MEAN^ROSETTA
No data
Line 2,185 ⟶ 2,470:
 
=={{header|Nanoquery}}==
<langsyntaxhighlight Nanoquerylang="nanoquery">def sum(lst)
sum = 0
for n in lst
Line 2,195 ⟶ 2,480:
def average(x)
return sum(x) / len(x)
end</langsyntaxhighlight>
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
using Nemerle.Collections;
Line 2,214 ⟶ 2,499:
WriteLine("Mean of [1 .. 10]: {0}", ArithmeticMean($[1 .. 10]));
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,268 ⟶ 2,553:
]
return vectors
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 2,292 ⟶ 2,577:
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">(define (Mean Lst)
(if (empty? Lst)
0
Line 2,298 ⟶ 2,583:
(Mean (sequence 1 1000))-> 500
(Mean '()) -> 0</langsyntaxhighlight>
 
=={{header|Nial}}==
in the standard way, mean is
<langsyntaxhighlight lang="nial">mean is / [sum, tally]
 
mean 6 2 4
= 4</langsyntaxhighlight>
but it fails with 0 length vectors. so using a tally with a minimum value 1
 
<langsyntaxhighlight lang="nial">dtally is recur [ empty rest, 1 first, 1 first, plus, rest ]
mean is / [sum, dtally]
 
mean []
=0</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|C}}
<langsyntaxhighlight lang="nim">import strutils
 
proc mean(xs: openArray[float]): float =
Line 2,326 ⟶ 2,611:
for i in 0..5:
echo "mean of first ", v.len, " = ", formatFloat(mean(v), precision = 0)
if v.len > 0: v.setLen(v.high)</langsyntaxhighlight>
Output:
<pre>mean of first 5 = 2.372
Line 2,336 ⟶ 2,621:
 
=={{header|Niue}}==
<syntaxhighlight lang="niue">
<lang Niue>
[ [ , len 1 - at ! ] len 3 - times swap , ] 'map ; ( a Lisp like map, to sum the stack )
[ len 'n ; [ + ] 0 n swap-at map n / ] 'avg ;
Line 2,344 ⟶ 2,629:
3.4 2.3 .01 2.0 2.1 avg .
=> 1.9619999999999997
</syntaxhighlight>
</lang>
 
=={{header|Oberon-2}}==
Oxford Oberon-2
<langsyntaxhighlight lang="oberon2">
MODULE AvgMean;
IMPORT Out;
Line 2,378 ⟶ 2,663:
Out.Fixed(Avg(ary),4,2);Out.Ln
END AvgMean.
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,385 ⟶ 2,670:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
function : native : PrintAverage(values : FloatVector) ~ Nil {
values->Average()->PrintLine();
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
These functions return a float:
 
<langsyntaxhighlight lang="ocaml">let mean_floats = function
| [] -> 0.
| xs -> List.fold_left (+.) 0. xs /. float_of_int (List.length xs)
 
let mean_ints xs = mean_floats (List.map float_of_int xs)</langsyntaxhighlight>
 
the previous code is easier to read and understand, though if you wish
Line 2,410 ⟶ 2,695:
would rather be handled by an exception.
 
<langsyntaxhighlight lang="ocaml">let mean_floats xs =
if xs = [] then
invalid_arg "empty list"
Line 2,433 ⟶ 2,718:
in
(float total /. length)
;;</langsyntaxhighlight>
 
=={{header|Octave}}==
Line 2,439 ⟶ 2,724:
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:
 
<langsyntaxhighlight lang="octave">function m = omean(l)
if ( numel(l) == 0 )
m = 0;
Line 2,448 ⟶ 2,733:
 
disp(omean([]));
disp(omean([1,2,3]));</langsyntaxhighlight>
 
If the data contains missing value, encoded as non-a-number:
 
<langsyntaxhighlight lang="octave">function m = omean(l)
n = sum(~isnan(l));
l(isnan(l))=0;
s = sum(l);
m = s./n;
end;</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: avg ( x -- avg )
x sum
x size dup ifZero: [ 2drop null ] else: [ >float / ]
;</langsyntaxhighlight>
 
{{out}}
Line 2,475 ⟶ 2,760:
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
<lang ooRexx>
call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11)
Line 2,497 ⟶ 2,782:
end
return sum/numbers~items
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,515 ⟶ 2,800:
=={{header|Oz}}==
A version working on floats:
<langsyntaxhighlight lang="oz">declare
fun {Mean Xs}
{FoldL Xs Number.'+' 0.0} / {Int.toFloat {Length Xs}}
end
in
{Show {Mean [3. 1. 4. 1. 5. 9.]}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">avg(v)={
if(#v,vecsum(v)/#v)
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program Mean;
 
function DoMean(vector: array of double): double;
Line 2,557 ⟶ 2,842:
writeln (']');
writeln('Mean: ', DoMean(vector):10:8);
end.</langsyntaxhighlight>
 
Output:
Line 2,568 ⟶ 2,853:
Alternative version using the Math unit:
 
<langsyntaxhighlight lang="pascal">Program DoMean;
uses math;
const
Line 2,585 ⟶ 2,870:
mean := sum(vector)/length(vector);
writeln('Mean: ', mean:10:8);
end.</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub avg {
@_ or return 0;
my $sum = 0;
Line 2,595 ⟶ 2,880:
}
print avg(qw(3 1 4 1 5 9)), "\n";</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function mean(sequence s)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
if length(s)=0 then return 0 end if
<span style="color: #008080;">function</span> <span style="color: #000000;">mean</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
return sum(s)/length(s)
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end function
<span style="color: #008080;">return</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)/</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
? mean({1, 2, 5, -5, -9.5, 3.14159})</lang>
<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}}==
<langsyntaxhighlight Phixmontilang="phixmonti">1 2 5 -5 -9.5 3.14159 stklen tolist
len swap sum swap / print</langsyntaxhighlight>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">$nums = array(3, 1, 4, 1, 5, 9);
if ($nums)
echo array_sum($nums) / count($nums), "\n";
else
echo "0\n";</langsyntaxhighlight>
 
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">mean([]) = false.
mean(V) = sum(V) / len(V).</syntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de mean (Lst)
(if (atom Lst)
0
(/ (apply + Lst) (length Lst)) ) )</langsyntaxhighlight>
Output:
<pre>: (mean (range 1 1000))
Line 2,626 ⟶ 2,919:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">arithmetic_mean = sum(A)/dimension(A,1);</langsyntaxhighlight>
 
=={{header|Plain English}}==
<langsyntaxhighlight lang="plainenglish">To run:
Start up.
Demonstrate finding the arithmetic mean.
Line 2,678 ⟶ 2,971:
If the entry's next is not nil, append ", " to the string.
Put the entry's next into the entry.
Repeat.</langsyntaxhighlight>
{{out}}
<pre>
Line 2,687 ⟶ 2,980:
=={{header|Pop11}}==
 
<langsyntaxhighlight lang="pop11">define mean(v);
lvars n = length(v), i, s = 0;
if n = 0 then
Line 2,697 ⟶ 2,990:
endif;
return(s/n);
enddefine;</langsyntaxhighlight>
 
=={{header|PostScript}}==
<syntaxhighlight lang="text">
/findmean{
/x exch def
Line 2,716 ⟶ 3,009:
sum ==
}def
</syntaxhighlight>
</lang>
 
{{libheader|initlib}}
{{works with|Ghostscript}}
<langsyntaxhighlight lang="postscript">
/avg {
dup length
Line 2,729 ⟶ 3,022:
} ifte
}.
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
The hard way by calculating a sum and dividing:
<langsyntaxhighlight lang="powershell">function mean ($x) {
if ($x.Count -eq 0) {
return 0
Line 2,743 ⟶ 3,036:
return $sum / $x.Count
}
}</langsyntaxhighlight>
or, shorter, by using the <code>Measure-Object</code> cmdlet which already knows how to compute an average:
<langsyntaxhighlight lang="powershell">function mean ($x) {
if ($x.Count -eq 0) {
return 0
Line 2,751 ⟶ 3,044:
return ($x | Measure-Object -Average).Average
}
}</langsyntaxhighlight>
 
=={{header|Processing}}==
<syntaxhighlight lang="processing">float mean(float[] arr) {
float out = 0;
for (float n : arr) {
out += n;
}
return out / arr.length;
}</syntaxhighlight>
 
=={{header|Prolog}}==
Line 2,757 ⟶ 3,059:
{{works with|SWI-Prolog|6.6}}
 
<langsyntaxhighlight lang="prolog">
mean(List, Mean) :-
length(List, Length),
sumlist(List, Sum),
Mean is Sum / Length.
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure.d mean(List number())
Protected sum=0
 
Line 2,773 ⟶ 3,075:
ProcedureReturn sum / ListSize(number())
; Depends on programm if zero check needed, returns nan on division by zero
EndProcedure</langsyntaxhighlight>
 
=={{header|Python}}==
{{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
<langsyntaxhighlight lang="python">from math import fsum
def average(x):
return fsum(x)/float(len(x)) if x else 0
print (average([0,0,3,1,4,1,5,9,0,0]))
print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))</langsyntaxhighlight>
 
{{out}}
<langsyntaxhighlight lang="python">2.3
2.3</langsyntaxhighlight>
 
 
{{works with|Python|2.5}}
<langsyntaxhighlight lang="python">def average(x):
return sum(x)/float(len(x)) if x else 0
print (average([0,0,3,1,4,1,5,9,0,0]))
print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))</langsyntaxhighlight>
 
{{out}}
(Notice how the second call gave the wrong result)
<langsyntaxhighlight lang="python">2.3
1e-21</langsyntaxhighlight>
 
 
{{works with|Python|2.4}}
<langsyntaxhighlight lang="python">def avg(data):
if len(data)==0:
return 0
else:
return sum(data)/float(len(data))
print avg([0,0,3,1,4,1,5,9,0,0])</langsyntaxhighlight>
 
{{out}}
<syntaxhighlight lang ="python">2.3</langsyntaxhighlight>
 
{{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.)
<langsyntaxhighlight lang="python">>>> from statistics import mean
>>> mean([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20])
2.3
Line 2,823 ⟶ 3,125:
>>> big = 10**10000
>>> mean([Decimal(big), Decimal(-big), 3, 1, 4, 1, 5, 9, 1/Decimal(big), -1/Decimal(big)])
Decimal('2.3')</langsyntaxhighlight>
 
=={{header|Q}}==
A built-in solution is <tt>avg</tt>. An implementation of it could be:
<langsyntaxhighlight lang="q">mean:{(sum x)%count x}</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
Using the Quackery big number rational arithmetic library <code>bigrat.qky</code>.
 
<syntaxhighlight lang="quackery"> [ $ 'bigrat.qky' loadfile ] now!
[ [] swap times
[ 20001 random 10000 -
n->v 100 n->v v/
join nested join ] ] is makevector ( --> [ )
[ witheach
[ unpack
2 point$ echo$
i 0 > if
[ say ", " ] ] ] is echodecs ( [ --> )
 
[ dup size n->v rot
0 n->v rot
witheach
[ unpack v+ ]
2swap v/ ] is arithmean ( [ --> n/d )
 
[ 5 makevector
say "Internal representation of a randomly generated vector" cr
say "of five rational numbers. They are distributed between" cr
say "-100.00 and +100.00 and are multiples of 0.01."
cr cr dup echo cr cr
say "Shown as decimal fractions."
cr cr dup echodecs cr cr
arithmean
say "Arithmetic mean of vector as a decimal fraction to" cr
say "5 places after the point, as a rounded proper" cr
say "fraction with the denominator not exceeding 10, and" cr
say "finally as a vulgar fraction without rounding." cr cr
2dup 5 point$ echo$
say ", "
2dup proper 10 round improper
proper$ echo$
say ", "
vulgar$ echo$ cr cr
say "The same, but with a vector of 9973 rational numbers," cr
say "20 decimal places and a denominator not exceeding 100." cr cr
9973 makevector arithmean
2dup 20 point$ echo$
say ", "
2dup proper 100 round improper
proper$ echo$
say ", "
vulgar$ echo$ cr ] is demonstrate ( --> )</syntaxhighlight>
 
{{out}}
 
<pre>Internal representation of a randomly generated vector
of five rational numbers. They are distributed between
-100.00 and +100.00 and are multiples of 0.01.
[ [ -1999 100 ] [ 253 50 ] [ 2867 50 ] [ 3929 50 ] [ -25 2 ] ]
Shown as decimal fractions.
-19.99, 5.06, 57.34, 78.58, -12.5
Arithmetic mean of vector as a decimal fraction to
5 places after the point, as a rounded proper
fraction with the denominator not exceeding 10, and
finally as a vulgar fraction without rounding.
21.698, 21 7/10, 10849/500
The same, but with a vector of 9973 rational numbers,
20 decimal places and a denominator not exceeding 100.
-0.41664995487817106187, -5/12, -16621/39892</pre>
 
=={{header|R}}==
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:
 
<langsyntaxhighlight lang="rsplus">omean <- function(v) {
m <- mean(v)
ifelse(is.na(m), 0, m)
}</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 2,841 ⟶ 3,224:
Racket's math library (available in v5.3.2 and newer) comes with a <tt>mean</tt> function that works on arbitrary sequences.
 
<langsyntaxhighlight lang="racket">
#lang racket
(require math)
Line 2,848 ⟶ 3,231:
(mean '(2 2 4 4)) ; -> 3
(mean #(3 4 5 8)) ; -> 5
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 2,854 ⟶ 3,237:
{{works with|Rakudo|2015.10-11}}
 
<syntaxhighlight lang="raku" perl6line>multi mean([]){ Failure.new('mean on empty list is not defined') }; # Failure-objects are lazy exceptions
multi mean (@a) { ([+] @a) / @a }</langsyntaxhighlight>
 
=={{header|Rapira}}==
<syntaxhighlight lang="rapira">fun mean(arr)
sum := 0
for N from 1 to #arr do
sum := sum + arr[N]
od
return (sum / #arr)
end</syntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">rebol [
Title: "Arithmetic Mean (Average)"
URL: http://rosettacode.org/wiki/Average/Arithmetic_mean
Line 2,876 ⟶ 3,268:
print [mold x: [3 1 4 1 5 9] "->" average x]
print [mold x: [1000 3 1 4 1 5 9 -1000] "->" average x]
print [mold x: [1e20 3 1 4 1 5 9 -1e20] "->" average x]</langsyntaxhighlight>
 
Output:
Line 2,884 ⟶ 3,276:
[1000 3 1 4 1 5 9 -1000] -> 2.875
[1E+20 3 1 4 1 5 9 -1E+20] -> 0.0</pre>
 
=={{header|Red}}==
Red comes with the <code>average</code> function.
<syntaxhighlight lang="red">Red ["Arithmetic mean"]
 
print average []
print average [2 3 5]</syntaxhighlight>
{{out}}
<pre>
none
3.333333333333334
</pre>
 
The source code for <code>average</code>:
<syntaxhighlight lang="red">average: func [
"Returns the average of all values in a block"
block [block! vector! paren! hash!]
][
if empty? block [return none]
divide sum block to float! length? block
]</syntaxhighlight>
 
=={{header|ReScript}}==
 
<syntaxhighlight lang="rescript">let arr = [3, 8, 4, 1, 5, 12]
 
let num = Js.Array.length(arr)
let tot = Js.Array.reduce(\"+", 0, arr)
let mean = float_of_int(tot) /. float_of_int(num)
 
Js.log(Js.Float.toString(mean))</syntaxhighlight>
{{out}}
<pre>
$ bsc arithmean.res > arithmean.js
$ node arithmean.js
5.5
</pre>
 
=={{header|REXX}}==
Line 2,889 ⟶ 3,318:
 
A check is made to validate if the numbers in the list are all numeric.
<langsyntaxhighlight 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.?*/
@.1 = 10 9 8 7 6 5 4 3 2 1
Line 2,915 ⟶ 3,344:
 
if #==0 then return 'N/A: ───[no numeric values.]' /*No nums? Return N/A*/
return $ / # /*return the average. */</langsyntaxhighlight>
'''output''' &nbsp; when using the (internal) lists:
<pre>
Line 2,950 ⟶ 3,379:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
nums = [1,2,3,4,5,6,7,8,9,10]
sum = 0
Line 2,960 ⟶ 3,389:
next
return sum/len(numbers)
</syntaxhighlight>
</lang>
 
=={{header|RPL/2}}==
This is based on the dc version above.
{{works with|HP|48G}}
≪ DUP 'N' STO →LIST ΣLIST N / 'N' PURGE ≫ '<span style="color:blue">AMEAN</span>' STO
or,by using the stack instead of a temporary variable:
≪ →LIST ΣLIST LASTARG SIZE / ≫ '<span style="color:blue">AMEAN</span>' STO
 
CLEAR 1 2 3 5 7 DEPTH <span style="color:blue">AMEAN</span>
This is a simple rewrite of the dc version above. This works on an HP 48. "->" is a single right arrow character on the 48. Feel free to alter this code as necessary to work on RPL/2.
 
===Hard-working approach===
<lang rpl/2>1 2 3 5 7
Works for all RPL versions.
AMEAN
≪ DUP SIZE SWAP OVER
<< DEPTH DUP 'N' STO ->LIST ΣLIST N / >>
0 1 ROT '''FOR''' j
3.6</lang>
OVER j GET + '''NEXT'''
ROT / SWAP DROP
===Hard-working approach with local variables===
No significant impact on program size or speed, but much more readable
≪ DUP SIZE → vector n
≪ 0 1 n '''FOR''' j
vector j GET + '''NEXT'''
n /
≫ ≫
===Straightforward approach===
The dot product of any vector with [1 1 ... 1] gives the sum of its elements.
≪ SIZE LAST DUP 1 CON DOT SWAP / ≫
''''AMEAN'''' STO
 
===Using built-in statistics features===
Most of the code is dedicated to store the input array according to built-in statistics requirements, which requires a matrix with one line per record. Main benefit of this approach is that you can then easily calculate standard deviation and variance by calling resp. <code>SDEV</code> and <code>VAR</code> functions.
≪ { 1 } OVER SIZE + RDM TRN '∑DAT' STO MEAN ≫ ''''AMEAN'''' STO
 
[ 1 5 0 -4 6 ] '''AMEAN'''
{{out}}
<pre>
1: 1.6
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def mean(nums)
nums.sum(0.0) / nums.size
end
Line 2,980 ⟶ 3,438:
ary = nums[0,i]
puts "array size #{ary.size} : #{mean(ary)}"
end</langsyntaxhighlight>
{{out}}
<pre>
Line 2,993 ⟶ 3,451:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">print "Gimme the number in the array:";input numArray
dim value(numArray)
for i = 1 to numArray
Line 3,003 ⟶ 3,461:
next
if totValue <> 0 then mean = totValue/numArray
print "The mean is: ";mean</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn sum(arr: &[f64]) -> f64 {
arr.iter().fold(0.0, |p,&q| p + q)
}
Line 3,020 ⟶ 3,478:
let w = &[];
println!("mean of {:?}: {:?}", w, mean(w));
}</langsyntaxhighlight>
Output:
<pre>mean of [2, 3, 5, 7, 13, 21, 33, 54]: 17.25
Line 3,027 ⟶ 3,485:
=={{header|Sather}}==
Built to work with VEC, ("geometric" vectors), whose elements must be floats. A 0-dimension vector yields "nan".
<langsyntaxhighlight lang="sather">class VECOPS is
mean(v:VEC):FLT is
m ::= 0.0;
Line 3,040 ⟶ 3,498:
#OUT + VECOPS::mean(v) + "\n";
end;
end;</langsyntaxhighlight>
 
=={{header|Scala}}==
Using Scala 2.7, this has to be defined for each numeric type:
 
<langsyntaxhighlight lang="scala">def mean(s: Seq[Int]) = s.foldLeft(0)(_+_) / s.size</langsyntaxhighlight>
 
However, Scala 2.8 gives much more flexibility, but you still have to opt
between integral types and fractional types. For example:
 
<langsyntaxhighlight lang="scala">def mean[T](s: Seq[T])(implicit n: Integral[T]) = {
import n._
s.foldLeft(zero)(_+_) / fromInt(s.size)
}</langsyntaxhighlight>
 
This can be used with any subclass of <tt>Sequence</tt> on integral types, up
Line 3,063 ⟶ 3,521:
Alas, Scala 2.8 also simplifies the task in another way:
 
<langsyntaxhighlight lang="scala">def mean[T](s: Seq[T])(implicit n: Fractional[T]) = n.div(s.sum, n.fromInt(s.size))</langsyntaxhighlight>
 
Here we show a function that supports fractional types. Instead of importing the definitions
Line 3,071 ⟶ 3,529:
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define (mean l)
(if (null? l)
0
(/ (apply + l) (length l))))</langsyntaxhighlight>
 
> (mean (list 3 1 4 1 5 9))
Line 3,080 ⟶ 3,538:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
 
Line 3,103 ⟶ 3,561:
begin
writeln(mean(numVector));
end func;</langsyntaxhighlight>
 
=={{header|SenseTalk}}==
SenseTalk has a built-in average function.
<syntaxhighlight lang="sensetalk">put the average of [12,92,-17,66,128]
 
put average(empty)
</syntaxhighlight>
{{out}}
<pre>
56.2
nan
</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func avg(Array list) {
list.len > 0 || return 0;
list.sum / list.len;
}
 
say avg([Math.infInf, Math.infInf]);
say avg([3,1,4,1,5,9]);
say avg([1e+20, 3, 1, 4, 1, 5, 9, -1e+20]);
say avg([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0.11]);
say avg([10, 20, 30, 40, 50, -100, 4.7, -1100]);</langsyntaxhighlight>
{{out}}
<pre>inf
Inf
3.833333333333333333333333333333333333333
3.83333333333333333333333333333333333333333333333
2.875
3.674
-130.6625</pre>
</pre>
 
=={{header|Slate}}==
<langsyntaxhighlight 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: {}.</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">
| numbers |
 
Line 3,138 ⟶ 3,610:
(numbers inject: 0 into: [:sumSoFar :eachElement | sumSoFar + eachElement]) / numbers size ]
) 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):
<langsyntaxhighlight lang="smalltalk">
| numbers |
 
numbers := #(1 2 3 4 5 6 7 8).
( 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:
{{works with|Pharo}}
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">
| numbers |
 
numbers := #(1 2 3 4 5 6 7 8).
(numbers sum / numbers size) displayNl.
</syntaxhighlight>
</lang>
or
<langsyntaxhighlight lang="smalltalk">
| numbers |
 
numbers := #(1 2 3 4 5 6 7 8).
numbers average displayNl.
</syntaxhighlight>
</lang>
 
=={{header|SNOBOL4}}==
Line 3,169 ⟶ 3,641:
{{works with|CSnobol}}
<langsyntaxhighlight SNOBOL4lang="snobol4"> define('avg(a)i,sum') :(avg_end)
avg i = i + 1; sum = sum + a<i> :s(avg)
avg = 1.0 * sum / prototype(a) :(return)
Line 3,182 ⟶ 3,654:
output = '[' str '] -> ' avg(arr)
output = '[ ] -> ' avg(empty)
end</langsyntaxhighlight>
 
Output:
Line 3,190 ⟶ 3,662:
=={{header|SQL}}==
Tested on Oracle 11gR2, the more limited the tool, the more resourceful one becomes :)
<syntaxhighlight lang="sql">
<lang SQL>
create table "numbers" ("datapoint" integer);
 
Line 3,196 ⟶ 3,668:
 
select sum("datapoint")/count(*) from "numbers";
</syntaxhighlight>
</lang>
...or...
<langsyntaxhighlight SQLlang="sql">select avg("datapoint") from "numbers";</langsyntaxhighlight>
 
=={{header|Standard ML}}==
These functions return a real:
 
<langsyntaxhighlight lang="sml">fun mean_reals [] = 0.0
| mean_reals xs = foldl op+ 0.0 xs / real (length xs);
 
val mean_ints = mean_reals o (map real);</langsyntaxhighlight>
 
The previous code is easier to read and understand, though if you want
Line 3,216 ⟶ 3,688:
would rather be handled by an exception.
 
<langsyntaxhighlight lang="sml">fun mean_reals [] = raise Empty
| mean_reals xs = let
val (total, length) =
Line 3,235 ⟶ 3,707:
in
(real total / length)
end;</langsyntaxhighlight>
 
=={{header|Stata}}==
=== Mean of a dataset variable ===
Illustration of the mean on the population (in millions) in january 2016 of a few european countries (source [http://appsso.eurostat.ec.europa.eu/nui/show.do?dataset=demo_gind&lang=fr Eurostat]).
<syntaxhighlight lang="text">clear all
input str20 country population
Belgium 11311.1
Line 3,270 ⟶ 3,742:
. quietly summarize population
. display r(mean)
16715.75</langsyntaxhighlight>
 
=== Mean in Mata ===
<langsyntaxhighlight lang="stata">mata
a=11311.1\7153.8\10553.8\5707.3\
82175.7\1315.9\4724.7\10783.7
 
mean(a)
16715.75</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">func meanDoubles(s: [Double]) -> Double {
return s.reduce(0, +) / Double(s.count)
}
func meanInts(s: [Int]) -> Double {
return meanDoubles(s.map{Double($0)})
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
proc mean args {
if {[set num [llength $args]] == 0} {return 0}
expr {[tcl::mathop::+ {*}$args] / double($num)}
}
mean 3 1 4 1 5 9 ;# ==> 3.8333333333333335</langsyntaxhighlight>
 
=={{header|TI-83 BASIC}}==
<syntaxhighlight lang ="ti83b">Mean(Ans</langsyntaxhighlight>
 
=={{header|TI-89 BASIC}}==
 
<langsyntaxhighlight lang="ti89b">Define rcmean(nums) = when(dim(nums) = 0, 0, mean(nums))</langsyntaxhighlight>
 
=={{header|Trith}}==
<langsyntaxhighlight lang="trith">: mean dup empty? [drop 0] [dup [+] foldl1 swap length /] branch ;
 
[3 1 4 1 5 9] mean</langsyntaxhighlight>
 
=={{header|TypeScript}}==
<langsyntaxhighlight lang="typescript">
function mean(numbersArr)
{
Line 3,325 ⟶ 3,797:
alert( mean( [1,2,3,4,5] ) );
alert( mean( [] ) );
</syntaxhighlight>
</lang>
 
=={{header|UNIX Shell}}==
1) First solution with bash (V >= 3), works with floats :
<langsyntaxhighlight lang="bash1">echo "`cat f | paste -sd+ | bc -l` / `cat f | wc -l`" | bc -l
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang="bash1">cat f
1
2
Line 3,353 ⟶ 3,825:
echo "`cat f | paste -sd+ | bc -l`/`cat f | wc -l`" |bc -l
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.
 
<langsyntaxhighlight lang="bash">mean() {
if expr $# >/dev/null; then
(count=0
Line 3,380 ⟶ 3,852:
printf "test 4: "; mean -400 400 -1300 200 # -275
printf "test 5: "; mean - # expr: syntax error
printf "test 6: "; mean 1 2 A 3 # expr: non-numeric argument</langsyntaxhighlight>
 
=={{header|UnixPipes}}==
Line 3,387 ⟶ 3,859:
Uses [[ksh93]]-style process substitution. Also overwrites the file named <tt>count</tt> in the current directory.
{{works with|bash}}
<langsyntaxhighlight lang="bash">term() {
b=$1;res=$2
echo "scale=5;$res+$b" | bc
Line 3,408 ⟶ 3,880:
}
 
(echo 3; echo 1; echo 4) | mean</langsyntaxhighlight>
 
=={{header|Ursa}}==
<langsyntaxhighlight lang="ursa">#
# arithmetic mean
#
Line 3,421 ⟶ 3,893:
end for
 
out (/ (+ input) (size input)) endl console</langsyntaxhighlight>
 
=={{header|Ursala}}==
There is a library function for means already, although it doesn't cope with
empty vectors. A mean function could be defined as shown for this task.
<langsyntaxhighlight Ursalalang="ursala">#import nat
#import flo
 
Line 3,433 ⟶ 3,905:
#cast %e
 
example = mean <5.,3.,-2.,6.,-4.></langsyntaxhighlight>
output:
<pre>1.600000e+00</pre>
 
=={{header|V}}==
<langsyntaxhighlight lang="v">[mean
[sum 0 [+] fold].
dup sum
swap size [[1 <] [1]] when /
].</langsyntaxhighlight>
 
=={{header|Vala}}==
Using array to hold the numbers of the list:
<langsyntaxhighlight lang="vala">
double arithmetic(double[] list){
double mean;
Line 3,472 ⟶ 3,944:
stdout.printf("%s\n", mean_zero.to_string());
}
</syntaxhighlight>
</lang>
 
Output:
Line 3,481 ⟶ 3,953:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Private Function mean(v() As Double, ByVal leng As Integer) As Variant
Dim sum As Double, i As Integer
sum = 0: i = 0
Line 3,508 ⟶ 3,980:
Debug.Print "] = "; mean(v, leng)
Next leng
End Sub</langsyntaxhighlight>{{out}}
<pre>mean[1; 2; 2,178; 3; 3,142] = 0
mean[1; 2; 2,178; 3] = 0
Line 3,517 ⟶ 3,989:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Function mean(arr)
size = UBound(arr) + 1
Line 3,529 ⟶ 4,001:
'Example
WScript.Echo mean(Array(3,1,4,1,5,9))
</syntaxhighlight>
</lang>
 
{{Out}}
Line 3,536 ⟶ 4,008:
=={{header|Vedit macro language}}==
The numeric data is stored in current edit buffer as ASCII strings, one value per line.
<langsyntaxhighlight lang="vedit">#1 = 0 // Sum
#2 = 0 // Count
BOF
Line 3,545 ⟶ 4,017:
}
if (#2) { #1 /= #2 }
Num_Type(#1)</langsyntaxhighlight>
 
=={{header|Vim Script}}==
Throws an exception if the list is empty.
<langsyntaxhighlight lang="vim">function Mean(lst)
if empty(a:lst)
throw "Empty"
Line 3,558 ⟶ 4,030:
endfor
return sum / len(a:lst)
endfunction</langsyntaxhighlight>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">import math
import arrays
fn main() {
for v in [
[]f64{}, // mean returns ok = false
[math.inf(1), math.inf(1)], // answer is +Inf
// answer is NaN, and mean returns ok = true, indicating NaN
// is the correct result
[math.inf(1), math.inf(-1)],
[f64(3), 1, 4, 1, 5, 9],
[f64(10), 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11],
[f64(10), 20, 30, 40, 50, -100, 4.7, -11e2],
] {
println("Vector: $v")
m := arrays.fold(v, 0.0, fn(r f64, v f64) f64 { return r+v })/v.len
println("Mean of $v.len numbers is $m\n")
}
}</syntaxhighlight>
{{out}}
<pre>Vector: []
Mean of 0 numbers is nan
 
Vector: [+inf, +inf]
Mean of 2 numbers is +inf
 
Vector: [+inf, -inf]
Mean of 2 numbers is nan
 
Vector: [3, 1, 4, 1, 5, 9]
Mean of 6 numbers is 3.8333333333333335
 
Vector: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0.11]
Mean of 15 numbers is 3.674
 
Vector: [10, 20, 30, 40, 50, -100, 4.7, -1100]
Mean of 8 numbers is -130.66</pre>
 
=={{header|Wart}}==
<langsyntaxhighlight lang="python">def (mean l)
sum.l / len.l</langsyntaxhighlight>
 
Example run:
Line 3,569 ⟶ 4,083:
 
=={{header|WDTE}}==
<langsyntaxhighlight WDTElang="wdte">let s => import 'stream';
let a => import 'arrays';
 
Line 3,575 ⟶ 4,089:
a.stream nums
-> s.reduce [0; 0] (@ s p n => [+ (a.at p 0) 1; + (a.at p 1) n])
-> (@ s p => / (a.at p 1) (a.at p 0));</langsyntaxhighlight>
 
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:
<langsyntaxhighlight WDTElang="wdte">mean [1; 2; 3] -- io.writeln io.stdout;</langsyntaxhighlight>
 
Output:
Line 3,586 ⟶ 4,100:
 
=={{header|Wortel}}==
<langsyntaxhighlight lang="wortel">@let {
; using a fork (sum divided-by length)
mean1 @(@sum / #)
Line 3,597 ⟶ 4,111:
!mean2 [3 1 4 1 5 9 2]
]]
}</langsyntaxhighlight>
Returns:
<pre>[3.5714285714285716 3.5714285714285716]</pre>
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">class Arithmetic {
static mean(arr) {
if (arr.count == 0) Fiber.abort("Length must be greater than zero")
Line 3,608 ⟶ 4,122:
}
}
Arithmetic.mean([1,2,3,4,5]) // 3</langsyntaxhighlight>
 
=={{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>.
<langsyntaxhighlight lang="lisp">(defun mean (v)
(if (= (vector-length v) 0)
nil
(let ((l (vector->list v)))
(/ (apply + l) (length l)))))</langsyntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code CrLf=9;
code real RlOut=48;
 
Line 3,635 ⟶ 4,149:
[Test:= [1.0, 2.0, 5.0, -5.0, 9.5, 3.14159];
RlOut(0, Mean(Test, 6)); CrLf(0);
]</langsyntaxhighlight>
 
Output:
Line 3,646 ⟶ 4,160:
Where <code>$values</code> is some variable indicating a set of nodes containing numbers, the average is given by the XPath expression:
 
<langsyntaxhighlight lang="xpath">sum($values) div count($values)</langsyntaxhighlight>
 
===Runnable example===
 
<langsyntaxhighlight lang="xml"><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="text"/>
 
Line 3,657 ⟶ 4,171:
<xsl:value-of select="sum($values) div count($values)"/>
</xsl:template>
</xsl:stylesheet></langsyntaxhighlight>
 
Sample input:
 
<langsyntaxhighlight lang="xml"><numbers>
<!-- Average is 2.4 -->
<number>1</number>
Line 3,668 ⟶ 4,182:
<number>3</number>
<number>5</number>
</numbers></langsyntaxhighlight>
 
=={{header|Yorick}}==
<langsyntaxhighlight lang="yorick">func mean(x) {
if(is_void(x)) return 0;
return x(*)(avg);
}</langsyntaxhighlight>
 
=={{header|zkl}}==
Converts int to floats (implicitly):
<langsyntaxhighlight 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(); //-->Exception thrown: MathError(NaN (Not a number))</langsyntaxhighlight>
To pass in a vector/list:
<langsyntaxhighlight lang="zkl">fcn meanV(z){ z.reduce('+,0.0)/z.len() }
meanV(T(3,1,4,1,5,9)); // --> 3.83333</langsyntaxhighlight>
 
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">
<lang Zoea>
program: average
case: 1
Line 3,694 ⟶ 4,208:
input: [7,11]
output: 9
</syntaxhighlight>
</lang>
 
=={{header|zonnon}}==
<langsyntaxhighlight lang="zonnon">
module Averages;
type
Line 3,715 ⟶ 4,229:
write("arithmetic mean: ");writeln(ArithmeticMean(x):10:2)
end Averages.
</syntaxhighlight>
</lang>
{{out}}
<pre>
885

edits