Averages/Arithmetic mean: Difference between revisions
m
syntax highlighting fixup automation
m (→{{header|Common Lisp}}: Corrected indentation) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 14:
=={{header|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>
{{out}}
<pre>
Line 28:
=={{header|11l}}==
{{trans|Python}}
<
R sum(x) / Float(x.len)
print(average([0, 0, 3, 1, 4, 1, 5, 9, 0, 0]))</
{{out}}
<pre>
Line 39:
=={{header|360 Assembly}}==
Compact and functional.
<
USING AVGP,12
LR 12,15
Line 65:
Z DC CL80' '
U DS CL2
END AVGP</
{{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.
<
TYA
PHA ;push accumulator and Y register onto stack
Line 111:
TAY
PLA
RTS ;return from routine</
=={{header|8th}}==
<
: avg \ a -- avg(a)
dup ' n:+ 0 a:reduce
Line 124:
[ 10 ] avg . cr
bye
</syntaxhighlight>
Output is:<br>
2.54395<br>
Line 131:
=={{header|ACL2}}==
<
(if (endp xs)
(mv 0 0)
Line 143:
(mv-let (n d)
(mean-r xs)
(/ n d))))</
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<
PROC Mean(INT ARRAY a INT count REAL POINTER result)
Line 191:
Test(a3,1)
Test(a3,0)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Arithmetic_mean.png Screenshot from Atari 8-bit computer]
Line 202:
=={{header|ActionScript}}==
<
{
var sum:Number = 0;
Line 208:
sum += vector[i];
return vector.length == 0 ? 0 : sum / vector.length;
}</
=={{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.
<
with Ada.Text_IO; use Ada.Text_IO;
Line 233:
Put(Item => Mean(A (1..0)), Fore => 1, Exp => 0);
New_Line;
end Mean_Main;</
Output:
3.83333
Line 240:
=={{header|Aime}}==
<
mean(list l)
{
Line 259:
0;
}</
=={{header|ALGOL 68}}==
Line 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.}}
<
# Calculates the mean of qty REALs beginning at p. #
IF LWB p > UPB p THEN 0.0
Line 279:
[6]REAL test := (1.0, 2.0, 5.0, -5.0, 9.5, 3.14159);
print((mean(test),new line))
)</
=={{header|ALGOL W}}==
<
% 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 303:
r_format := "A"; r_w := 10; r_d := 2; % set fixed point output %
write( mean( numbers, 1, 5 ) );
end.</
=={{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")
<
DEF m, i, ll
ll := ListLen(l)
Line 321:
WriteF('mean \s\n',
RealF(s,mean([1.0, 2.0, 3.0, 4.0, 5.0]), 2))
ENDPROC</
=={{header|AntLang}}==
AntLang has a built-in avg function.
<syntaxhighlight lang
=={{header|APL}}==
{{works with|APL2}}
<
(+/X)÷⍴X
3.833333333</
=={{header|AppleScript}}==
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.
<
set len to (count listOfNumbers)
if (len is 0) then return missing value
Line 350:
end average
average({2500, 2700, 2400, 2300, 2550, 2650, 2750, 2450, 2600, 2400})</
{{output}}
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
<
use framework "Foundation"
Line 369:
end average
average({2500, 2700, 2400, 2300, 2550, 2650, 2750, 2450, 2600, 2400})</
{{output}}
Line 375:
=={{header|Applesoft BASIC}}==
<
0 READ V$
1 IF LEN(V$) = 0 THEN END
Line 392:
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>
=={{header|Arturo}}==
<
print average arr</
{{out}}
Line 405:
=={{header|Astro}}==
<
mean(1..10)
mean([])
</syntaxhighlight>
=={{header|AutoHotkey}}==
<
Loop, % i {
Random, v, -3.141592, 3.141592
Line 417:
sum += v
}
MsgBox, % i ? list "`nmean: " sum/i:0</
=={{header|AWK}}==
<
#!/usr/local/bin/gawk -f
Line 444:
print mean(nothing)
}
</syntaxhighlight>
{{out}}
Line 455:
=={{header|Babel}}==
<
{{Out}}
Line 464:
Assume the numbers are in an array named "nums".
<
sum = 0;
FOR i = LBOUND(nums) TO UBOUND(nums)
Line 475:
ELSE
PRINT 0
END IF</
==={{header|BBC BASIC}}===
Line 481:
To calculate the mean of an array:
<
REM specific functions for the array/vector types
Line 510:
DEF FN_Mean_Arithmetic#(n#())
= SUM(n#()) / (DIM(n#(),1)+1)
</syntaxhighlight>
[[User:MichaelHutton|Michael Hutton]] 14:02, 29 May 2011 (UTC)
==={{header|IS-BASIC}}===
<
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 523:
170 NEXT
180 LET AM=T/SIZE(A)
190 END DEF</
=={{header|bc}}==
Uses the current scale for calculating the mean.
<
auto i, s
Line 534:
}
return(s / n)
}</
=={{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>.
<
@./\$_\&+\^</
=={{header|blz}}==
<
:mean(vec)
vec.fold_left(0, (x, y -> x + y)) / vec.length()
end</
=={{header|Bracmat}}==
Here are two solutions. The first uses a while loop, the second scans the input by backtracking.
<
(mean1=
sum length n
Line 574:
| !sum*!length^-1
);
</syntaxhighlight>
To test with a list of all numbers 1 .. 999999:
<
( :?test
& 1000000:?Length
Line 582:
& out$mean1$!test
& out$mean2$!test
)</
=={{header|Brat}}==
<
true? list.empty?, 0, { list.reduce(0, :+) / list.length }
}
p mean 1.to 10 #Prints 5.5</
=={{header|Burlesque}}==
<
blsq ) {1 2 2.718 3 3.142}av
2.372
blsq ) {}av
NaN
</syntaxhighlight>
=={{header|BQN}}==
Defines a tacit Avg function which works on any simple numeric list.
<
Avg 1‿2‿3‿4</
<lang>2.5</
[https://mlochbaum.github.io/BQN/try.html#code=QXZnIOKGkCArwrTDt+KJoAoKQXZnIDHigL8y4oC/M+KAvzQ= Try It!]
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>).
<
double mean(double *v, int len)
Line 636:
return 0;
}</
mean[1, 2, 2.718, 3, 3.142] = 2.372
mean[1, 2, 2.718, 3] = 2.1795
Line 646:
=={{header|C sharp|C#}}==
<
using System.Linq;
Line 655:
Console.WriteLine(new[] { 1, 2, 3 }.Average());
}
}</
Alternative version (not using the built-in function):
<
class Program
Line 686:
return d / nums.Length;
}
}</
=={{header|C++}}==
{{libheader|STL}}
<
double mean(const std::vector<double>& numbers)
Line 701:
sum += *i;
return sum / numbers.size();
}</
Shorter (and more idiomatic) version:
<
#include <algorithm>
Line 713:
return 0;
return std::accumulate(numbers.begin(), numbers.end(), 0.0) / numbers.size();
}</
Idiomatic version templated on any kind of iterator:
<
#include <algorithm>
Line 726:
return 0;
return std::accumulate(begin, end, 0.0) / std::distance(begin, end);
}</
=={{header|Chef}}==
<
Chef has no way to detect EOF, so rather than interpreting
Line 760:
Pour contents of mixing bowl into baking dish.
Serves 1.</
=={{header|Clojure}}==
Returns a [http://clojure.org/data_structures ratio]:
<
(if (empty? sq)
0
(/ (reduce + sq) (count sq))))</
Returns a float:
<
(if (empty? sq)
0
(float (/ (reduce + sq) (count sq)))))</
=={{header|COBOL}}==
Intrinsic function:
<
Sample implementation:
<
PROGRAM-ID. find-mean.
Line 808:
GOBACK
.</
=={{header|Cobra}}==
<
class Rosetta
def mean(ns as List<of number>) as number
Line 826:
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>
Output:
Line 835:
=={{header|CoffeeScript}}==
<
mean = (array) ->
return 0 if array.length is 0
Line 843:
alert mean [1]
</syntaxhighlight>
=={{header|Common Lisp}}==
'''With Reduce'''
<
(when sequence
(/ (reduce #'+ sequence) (length sequence))))</
'''With Loop'''
<
(when list
(/ (loop for i in list sum i)
(length list))))</
=={{header|Crystal}}==
<
def mean(arr) : Float64
arr.sum / arr.size.to_f
end</
=={{header|D}}==
===Imperative Version===
<
real sum = 0.0;
int count;
Line 888:
data = [3, 1, 4, 1, 5, 9];
writeln("Mean: ", data.mean);
}</
{{out}}
<pre>mean: 0
mean: 3.83333</pre>
===More Functional Version===
<
real mean(Range)(Range r) pure nothrow @nogc {
Line 902:
writeln("Mean: ", (int[]).init.mean);
writeln("Mean: ", [3, 1, 4, 1, 5, 9].mean);
}</
{{out}}
<pre>Mean: 0
Line 909:
===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):
<
CommonType!(T, real) mean(T)(T[] n ...) if (isNumeric!T) {
Line 922:
writefln("%8.5f", mean( 0, 3, 1, 4, 1, 5, 9, 0));
writefln("%8.5f", mean([-1e20, 3, 1, 4, 1, 5, 9, 1e20]));
}</
{{out}}
<pre> 0.00000
Line 929:
=={{header|Dart}}==
<
void main(){
print(mean([1,2,3,4,5,6,7]));
}</
{{out}}
<pre>4.0</pre>
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.
<
3.6</
An expanded example, identifying an empty sample set, could be created as a file, e.g., amean.cd:
<
zd0=qsn [stack length = n]sz
1k [precision can be altered]sz
[+z1<+]ds+x[Sum: ]Pp
ln/[Mean: ]Pp
[Sample size: ]Plnp</
By saving the sample set "1 2 3 5 7" in a file (sample.dc), the routine, listing summary information, could be called in a command line:
<
Sum: 18
Mean: 3.6
Sample size: 5
$</
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 982:
Writeln(Mean(TDoubleDynArray.Create()));
Writeln(Mean(TDoubleDynArray.Create(1,2,3,4,5)));
end.</
=={{header|Dyalect}}==
<
var acc = .0
var len = 0
Line 996:
}
avg(1, 2, 3, 4, 5, 6)</
=={{header|E}}==
Line 1,002:
Slightly generalized to support any object that allows iteration.
<
var count := 0
var sum := 0
Line 1,010:
}
return sum / 1.max(count)
}</
=={{header|EasyLang}}==
Line 1,021:
f[] = [ 1 2 3 4 5 6 7 8 ]
call mean f[] r
print r</
=={{header|EchoLisp}}==
'''(mean values)''' is included in math.lib. values may be a list, vector, sequence, or any kind of procrastinator.
<
(lib 'math)
(mean '(1 2 3 4)) ;; mean of a list
Line 1,047:
😁 warning: mean : zero-divide : empty-sequence
→ 0
</syntaxhighlight>
=={{header|ECL}}==
<
AveVal(SET OF INTEGER s) := AVE(s);
Line 1,057:
SetVals := [14,9,16,20,91];
AveVal(SetVals) //returns 30.0 ;
</syntaxhighlight>
=={{header|Elena}}==
ELENA 5.0:
<
extension op
Line 1,088:
"Arithmetic mean of {",array.asEnumerable(),"} is ",
array.average()).readChar()
}</
{{out}}
<pre>
Line 1,095:
=={{header|Elixir}}==
<
def mean(list), do: Enum.sum(list) / length(list)
end</
=={{header|Emacs Lisp}}==
<
(/ (float (apply '+ lst)) (length lst)))
(mean '(1 2 3 4))</
{{libheader|Calc}}
<
(calc-eval "vmean($1)" nil (append '(vec) x)))</
=={{header|Erlang}}==
<
mean(L) -> lists:sum(L)/erlang:length(L).</
=={{header|Euphoria}}==
<
atom sum
if length(s) = 0 then
Line 1,129:
sequence test
test = {1.0, 2.0, 5.0, -5.0, 9.5, 3.14159}
? mean(test)</
=={{header|Excel}}==
Assuming the values are entered in the A column, type into any cell which will not be part of the list:
<
Assuming 10 values will be entered, alternatively, you can just type:
<
and then select the start and end cells, not necessarily in the same row or column.
Line 1,159:
=={{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.
<
a + (1. / ((float n) + 1.)) * (v - a)
let mean_series list =
let a, _ = List.fold_left (fun (a, n) h -> avg a (float h) n, n + 1) (0., 0) list in
a</
Checking this:
<
val it : float = 10.86666667
> mean_series [] ;;
val it : float = 0.0</
We can also make do with the built-in ''List.average'' function:
<
=={{header|Factor}}==
<
: arithmetic-mean ( seq -- n )
[ 0 ] [ mean ] if-empty ;</
Tests:
<
3.333333333333333</
=={{header|Fantom}}==
<
class Main
{
Line 1,207:
}
}
</syntaxhighlight>
=={{header|Fish}}==
<
v< +<>0n; >n;
>l1)?^&,n;</
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,219:
=={{header|Forth}}==
<
0e
dup 0= if 2drop exit then
Line 1,228:
create test 3e f, 1e f, 4e f, 1e f, 5e f, 9e f,
test 6 fmean f. \ 3.83333333333333</
=={{header|Fortran}}==
In ISO Fortran 90 or later, use the SUM intrinsic, the SIZE intrinsic and the MAX intrinsic (to avoid divide by zero):
<
real, dimension(5,20) :: b = reshape( a, (/ 5,20 /) )
real, pointer, dimension(:) :: p => a(2:1) ! pointer to zero-length array
Line 1,251:
! 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)</
=={{header|FreeBASIC}}==
<
' FB 1.05.0 Win64
Line 1,297:
Print "Press any key to quit the program"
Sleep
</syntaxhighlight>
{{out}}
Line 1,319:
=={{header|Frink}}==
The following works on arrays or sets. If the collection is empty, this returns the special value <CODE>undef</CODE>.
<
mean[x] := length[x] > 0 ? sum[x] / length[x] : undef
</syntaxhighlight>
=={{header|GAP}}==
<
local n;
n := Length(v);
Line 1,335:
Mean([3, 1, 4, 1, 5, 9]);
# 23/6</
=={{header|GEORGE}}==
<
0
1, n rep (i)
Line 1,344:
]
n div
P</
Output:
<pre>
Line 1,388:
RETURN sum/size%
ENDFUNC
</syntaxhighlight>
=={{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.
<
import (
Line 1,457:
}
}
}</
{{out}}
<pre>
Line 1,483:
=={{header|Groovy}}==
<
Test Program:
<
println avg([2,2,2,4,2])
println avg ([])</
Output:
Line 1,497:
=={{header|Haskell}}==
This function works if the element type is an instance of Fractional:
<
mean [] = 0
mean xs = sum xs / Data.List.genericLength xs</
But some types, e.g. integers, are not Fractional; the following function works for all Real types:
<
meanReals = mean . map realToFrac</
If you want to avoid keeping the list in memory and traversing it twice:
<
import Data.List (foldl') --'
Line 1,525:
main :: IO ()
main = print $ mean [1 .. 100]</
=={{header|HicEst}}==
<
vec = $ - 1/2 ! 0.5 ... 99.5
mean = SUM(vec) / LEN(vec) ! 50
END </
=={{header|Hy}}==
Returns <tt>None</tt> if the input is of length zero.
<
(if xs
(/ (sum xs) (len xs))))</
=={{header|Icon}} and {{header|Unicon}}==
<
every (s := 0) +:= !args
write((real(s)/(0 ~= *args)) | 0)
end</
Sample outputs:
Line 1,557:
If truly only the mean is wanted, one could use
<
print,mean(x)</
But <tt>mean()</tt> is just a thin wrapper returning the zeroth element of <tt>moment()</tt> :
<
; ==>
3.83333 8.96667 0.580037 -1.25081</
which are mean, variance, skewness and kurtosis.
Line 1,572:
=={{header|J}}==
<
That is, sum divided by the number of items. The verb also works on higher-ranked arrays. For example:
<
3.83333
mean $0 NB. $0 is a zero-length vector
Line 1,582:
x=: 20 4 ?@$ 0 NB. a 20-by-4 table of random (0,1) numbers
mean x
0.58243 0.402948 0.477066 0.511155</
The computation can also be written as a loop. It is shown here for comparison only and is highly non-preferred compared to the version above.
<
z=. 0
for_i. i.#y do. z=. z+i{y end.
Line 1,596:
0
mean1 x
0.58243 0.402948 0.477066 0.511155</
=={{header|Java}}==
{{works with|Java|1.5+}}
<
double sum = 0.0;
for (double x : arr) {
Line 1,607:
}
return sum / arr.length;
}</
=={{header|JavaScript}}==
Line 1,613:
===ES5===
<
{
var sum = 0, i;
Line 1,624:
alert( mean( [1,2,3,4,5] ) ); // 3
alert( mean( [] ) ); // 0</
Using the native function `.forEach()`:
<
var sum = 0;
array.forEach(function(value){
Line 1,635:
}
alert( mean( [1,2,3,4,5] ) ); // 3</
Using the native function `.reduce()`:
<
return !array.length ? 0
: array.reduce(function(pre, cur, i) {
Line 1,647:
alert( mean( [1,2,3,4,5] ) ); // 3
alert( mean( [] ) ); // 0
</syntaxhighlight>
Extending the `Array` prototype:
<
return !this.length ? 0
: this.reduce(function(pre, cur, i) {
Line 1,659:
alert( [1,2,3,4,5].mean() ); // 3
alert( [].mean() ); // 0
</syntaxhighlight>
{{libheader|Functional}}
<
{
return a.length ? Functional.reduce('+', 0, a) / a.length : 0;
}</
===ES6===
<
// mean :: [Num] => (Num | NaN)
Line 1,684:
return mean(sample);
})([1, 2, 3, 4, 5, 6, 7, 8, 9]);</
{{Out}}
<syntaxhighlight lang
=={{header|jq}}==
The mean of an array of numbers can be computed by simply writing
<syntaxhighlight lang
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:
<
else add/length
end;</
=={{header|Julia}}==
Julia's built-in mean function accepts AbstractArrays (vector, matrix, etc.)
<
2.0
julia> mean(1:10)
5.5
julia> mean([])
ERROR: mean of empty collection undefined: []</
=={{header|K}}==
<
mean 1 2 3 5 7
3.6
mean@!0 / empty array
0.0</
=={{header|Kotlin}}==
Kotlin has builtin functions for some collection types.
Example:
<
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()))
}</
=={{header|KQL}}==
<
let dataset = datatable(values:real)[
1, 1.5, 3, 5, 6.5];
dataset|summarize avg(values)
</syntaxhighlight>
Output:
Line 1,741:
=={{header|Lambdatalk}}==
<
{def mean
{lambda {:s}
Line 1,750:
{mean {S.serie 0 1000}}
-> 500
</syntaxhighlight>
=={{header|langur}}==
Line 1,758:
{{works with|langur|0.6.6}}
<
writeln " custom: ", .mean([7, 3, 12])
writeln "built-in: ", mean([7, 3, 12])</
{{out}}
Line 1,768:
=={{header|Lasso}}==
<
not #a->size ? return 0
local(x = 0.0)
Line 1,775:
}
average(array(1,2,5,17,7.4)) //6.48</
=={{header|LFE}}==
Line 1,781:
=== 1-Arity ===
<
(defun mean (data)
(/ (lists:sum data)
(length data)))
</syntaxhighlight>
Usage:
<
1.0
> (mean '(1 2))
Line 1,795:
6.0
> (mean '(6 12 18 24 30 36 42 48 54 60 66 72 78))
42.0</
=== n-Arity ===
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:
<
`(/ (lists:sum ,args)
,(length args)))</
Usage:
<
42.0
> (mean 18 66)
42.0
> (mean 6 12 18 24 30 36 42 48 54 60 66 72 78)
42.0</
=={{header|Liberty BASIC}}==
<
dim nums(total)
for i = 1 to total
Line 1,826:
if total=0 then mean=0 else mean=sum/total
print "Arithmetic mean: ";mean
</
=={{header|Limbo}}==
<
include "sys.m";
Line 1,852:
n += a[i];
return n / (real len a);
}</
=={{header|Lingo}}==
<
on mean (v)
case ilk(v) of
Line 1,868:
end repeat
return float(sum)/cnt
end</
<
-- 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</
=={{header|LiveCode}}==
Livecode provides arithmeticMean (avg, average) built-in.
<
average(empty) -- 0</
=={{header|Logo}}==
<
if empty? :l [output 0]
output quotient apply "sum :l count :l
end
print average [1 2 3 4] ; 2.5</
=={{header|Logtalk}}==
Logtalk's standard library provides an arithmetic average predicate but we ignore it here. Representing a vector using a list:
<
:- object(averages).
Line 1,909:
:- end_object.
</syntaxhighlight>
Sample output:
<
| ?- averages::arithmetic([1,2,3,4,5,6,7,8,9,10], Mean).
Mean = 5.5
yes
</syntaxhighlight>
=={{header|LSL}}==
<
integer MAX_VALUE = 100;
default {
Line 1,939:
llOwnerSay(" Sum Squares: "+(string)llListStatistics(LIST_STAT_SUM_SQUARES, lst));
}
}</
Output:
<pre>
Line 1,956:
=={{header|Lua}}==
<
if type(numlist) ~= 'table' then return numlist end
num = 0
Line 1,963:
end
print (mean({3,1,4,1,5,9}))</
=={{header|Lucid}}==
<
where
sum = first(x) fby sum + next(x);
n = 1 fby n + 1;
avg = sum / n;
end</
=={{header|M4}}==
Line 1,980:
directly, but it is a little bit clearer to keep them separated.
<
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</
<
=={{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.
<
mean := proc( a :: indexable )
local i;
Normalizer( add( i, i in a ) / numelems( a ) )
end proc:
</syntaxhighlight>
For example:
<
> mean( { 1/2, 2/3, 3/4, 4/5, 5/6 } ); # set
71
Line 2,018:
> mean([]); # empty argument causes an exception to be raised.
Error, (in mean) numeric exception: division by zero
</syntaxhighlight>
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.
<
This can be called as in the following examples.
<
> mean( 1, 2, 3, 4, 5 );
3
Line 2,033:
> mean(); # again, an exception is raised
Error, (in mean) numeric exception: division by zero
</syntaxhighlight>
If desired, we can add argument type-checking as follows.
<
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Modify the built-in Mean function to give 0 for empty vectors (lists in Mathematica):
<
Mean[{}] := 0</
Examples:
<
Mean[{3.2,4.5,5.9}]
Mean[{-4, 1.233}]
Mean[{}]
Mean[{1/2,1/3,1/4,1/5}]
Mean[{a,c,Pi,-3,a}]</
gives (a set of integers gives back an integer or a rational, a set of floats gives back a float, a set of rationals gives a rational back, a list of symbols and numbers keeps the symbols exact and a mix of exact and approximate numbers gives back an approximate number):
<
4.53333
-1.3835
0
77/240
1/5 (-3+2 a+c+Pi)</
=={{header|Mathprog}}==
Line 2,091:
end;
</syntaxhighlight>
When run this produces:
Line 2,118:
The arithmetic mean of the integers from 1 to 1048575 is 524288.000000
Model has been successfully processed
</syntaxhighlight>
=={{header|MATLAB}}==
<
meanValue = mean(setOfValues);
end</
=={{header|Maxima}}==
<
mean([2, 7, 11, 17]);</
=={{header|MAXScript}}==
<
(
total = 0
Line 2,140:
)
print (mean #(3, 1, 4, 1, 5, 9))</
=={{header|Mercury}}==
<
:- interface.
Line 2,162:
mean(Ns @ [_ | _]) = foldl((+), Ns, 0.0) / float(length(Ns)).
:- end_module arithmetic_mean.</
Alternatively, we could use inst subtyping to ensure we get a compilation error if the
mean function is called with an empty list.
<
mean(Ns) = foldl((+), Ns, 0.0) / float(length(Ns)).</
=={{header|min}}==
Returns <code>nan</code> for an empty quotation.
{{works with|min|0.19.3}}
<
(2 3 5) mean print</
{{out}}
<pre>
Line 2,183:
=={{header|MiniScript}}==
<
avg = function(arr)
Line 2,193:
end function
print avg(arr)</
=={{header|МК-61/52}}==
<lang>0 П0 П1 С/П ИП0 ИП1 * + ИП1 1
+ П1 / П0 БП 03</
''Instruction:'' В/О С/П Number С/П Number ...
Line 2,204:
=={{header|Modula-2}}==
<
VAR avg : REAL;
Line 2,213:
InOut.WriteReal (avg, 8, 2);
InOut.WriteLn
END Avg;</
OR
<
(* Calculate the average over 'Samples' values, stored in array 'Data'. *)
Line 2,228:
END;
RETURN sum / FLOAT(Samples)
END Average;</
=={{header|MUMPS}}==
<
;X is assumed to be a list of numbers separated by "^"
QUIT:'$DATA(X) "No data"
Line 2,238:
SET S=0,I=1
FOR QUIT:I>$L(X,"^") SET S=S+$P(X,"^",I),I=I+1
QUIT (S/$L(X,"^"))</
<pre>USER>W $$MEAN^ROSETTA
No data
Line 2,250:
=={{header|Nanoquery}}==
<
sum = 0
for n in lst
Line 2,260:
def average(x)
return sum(x) / len(x)
end</
=={{header|Nemerle}}==
<
using System.Console;
using Nemerle.Collections;
Line 2,279:
WriteLine("Mean of [1 .. 10]: {0}", ArithmeticMean($[1 .. 10]));
}
}</
=={{header|NetRexx}}==
<
options replace format comments java crossref symbols nobinary
Line 2,333:
]
return vectors
</syntaxhighlight>
'''Output:'''
<pre>
Line 2,357:
=={{header|NewLISP}}==
<
(if (empty? Lst)
0
Line 2,363:
(Mean (sequence 1 1000))-> 500
(Mean '()) -> 0</
=={{header|Nial}}==
in the standard way, mean is
<
mean 6 2 4
= 4</
but it fails with 0 length vectors. so using a tally with a minimum value 1
<
mean is / [sum, dtally]
mean []
=0</
=={{header|Nim}}==
{{trans|C}}
<
proc mean(xs: openArray[float]): float =
Line 2,391:
for i in 0..5:
echo "mean of first ", v.len, " = ", formatFloat(mean(v), precision = 0)
if v.len > 0: v.setLen(v.high)</
Output:
<pre>mean of first 5 = 2.372
Line 2,401:
=={{header|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,409:
3.4 2.3 .01 2.0 2.1 avg .
=> 1.9619999999999997
</syntaxhighlight>
=={{header|Oberon-2}}==
Oxford Oberon-2
<
MODULE AvgMean;
IMPORT Out;
Line 2,443:
Out.Fixed(Avg(ary),4,2);Out.Ln
END AvgMean.
</syntaxhighlight>
Output:
<pre>
Line 2,450:
=={{header|Objeck}}==
<
function : native : PrintAverage(values : FloatVector) ~ Nil {
values->Average()->PrintLine();
}
</syntaxhighlight>
=={{header|OCaml}}==
These functions return a float:
<
| [] -> 0.
| xs -> List.fold_left (+.) 0. xs /. float_of_int (List.length xs)
let mean_ints xs = mean_floats (List.map float_of_int xs)</
the previous code is easier to read and understand, though if you wish
Line 2,475:
would rather be handled by an exception.
<
if xs = [] then
invalid_arg "empty list"
Line 2,498:
in
(float total /. length)
;;</
=={{header|Octave}}==
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:
<
if ( numel(l) == 0 )
m = 0;
Line 2,513:
disp(omean([]));
disp(omean([1,2,3]));</
If the data contains missing value, encoded as non-a-number:
<
n = sum(~isnan(l));
l(isnan(l))=0;
s = sum(l);
m = s./n;
end;</
=={{header|Oforth}}==
<
x sum
x size dup ifZero: [ 2drop null ] else: [ >float / ]
;</
{{out}}
Line 2,540:
=={{header|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,562:
end
return sum/numbers~items
</syntaxhighlight>
Output:
<pre>
Line 2,580:
=={{header|Oz}}==
A version working on floats:
<
fun {Mean Xs}
{FoldL Xs Number.'+' 0.0} / {Int.toFloat {Length Xs}}
end
in
{Show {Mean [3. 1. 4. 1. 5. 9.]}}</
=={{header|PARI/GP}}==
<
if(#v,vecsum(v)/#v)
};</
=={{header|Pascal}}==
<
function DoMean(vector: array of double): double;
Line 2,622:
writeln (']');
writeln('Mean: ', DoMean(vector):10:8);
end.</
Output:
Line 2,633:
Alternative version using the Math unit:
<
uses math;
const
Line 2,650:
mean := sum(vector)/length(vector);
writeln('Mean: ', mean:10:8);
end.</
=={{header|Perl}}==
<
@_ or return 0;
my $sum = 0;
Line 2,660:
}
print avg(qw(3 1 4 1 5 9)), "\n";</
=={{header|Phix}}==
<!--<
<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>
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>
<!--</
=={{header|Phixmonti}}==
<
len swap sum swap / print</
=={{header|PHP}}==
<
if ($nums)
echo array_sum($nums) / count($nums), "\n";
else
echo "0\n";</
=={{header|PicoLisp}}==
<
(if (atom Lst)
0
(/ (apply + Lst) (length Lst)) ) )</
Output:
<pre>: (mean (range 1 1000))
Line 2,694:
=={{header|PL/I}}==
<
=={{header|Plain English}}==
<
Start up.
Demonstrate finding the arithmetic mean.
Line 2,746:
If the entry's next is not nil, append ", " to the string.
Put the entry's next into the entry.
Repeat.</
{{out}}
<pre>
Line 2,755:
=={{header|Pop11}}==
<
lvars n = length(v), i, s = 0;
if n = 0 then
Line 2,765:
endif;
return(s/n);
enddefine;</
=={{header|PostScript}}==
Line 2,784:
sum ==
}def
</syntaxhighlight>
{{libheader|initlib}}
{{works with|Ghostscript}}
<
/avg {
dup length
Line 2,797:
} ifte
}.
</syntaxhighlight>
=={{header|PowerShell}}==
The hard way by calculating a sum and dividing:
<
if ($x.Count -eq 0) {
return 0
Line 2,811:
return $sum / $x.Count
}
}</
or, shorter, by using the <code>Measure-Object</code> cmdlet which already knows how to compute an average:
<
if ($x.Count -eq 0) {
return 0
Line 2,819:
return ($x | Measure-Object -Average).Average
}
}</
=={{header|Processing}}==
<
float out = 0;
for (float n : arr) {
Line 2,828:
}
return out / arr.length;
}</
=={{header|Prolog}}==
Line 2,834:
{{works with|SWI-Prolog|6.6}}
<
mean(List, Mean) :-
length(List, Length),
sumlist(List, Sum),
Mean is Sum / Length.
</syntaxhighlight>
=={{header|PureBasic}}==
<
Protected sum=0
Line 2,850:
ProcedureReturn sum / ListSize(number())
; Depends on programm if zero check needed, returns nan on division by zero
EndProcedure</
=={{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
<
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]))</
{{out}}
<
2.3</
{{works with|Python|2.5}}
<
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]))</
{{out}}
(Notice how the second call gave the wrong result)
<
1e-21</
{{works with|Python|2.4}}
<
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])</
{{out}}
<syntaxhighlight lang
{{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.)
<
>>> mean([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20])
2.3
Line 2,900:
>>> big = 10**10000
>>> mean([Decimal(big), Decimal(-big), 3, 1, 4, 1, 5, 9, 1/Decimal(big), -1/Decimal(big)])
Decimal('2.3')</
=={{header|Q}}==
A built-in solution is <tt>avg</tt>. An implementation of it could be:
<
=={{header|Quackery}}==
Line 2,910:
Using the Quackery big number rational arithmetic library <code>bigrat.qky</code>.
<
[ [] swap times
Line 2,961:
proper$ echo$
say ", "
vulgar$ echo$ cr ] is demonstrate ( --> )</
{{out}}
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:
<
m <- mean(v)
ifelse(is.na(m), 0, m)
}</
=={{header|Racket}}==
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.
<
#lang racket
(require math)
Line 3,006:
(mean '(2 2 4 4)) ; -> 3
(mean #(3 4 5 8)) ; -> 5
</syntaxhighlight>
=={{header|Raku}}==
Line 3,012:
{{works with|Rakudo|2015.10-11}}
<
multi mean (@a) { ([+] @a) / @a }</
=={{header|Rapira}}==
<
sum := 0
for N from 1 to #arr do
Line 3,022:
od
return (sum / #arr)
end</
=={{header|REBOL}}==
<
Title: "Arithmetic Mean (Average)"
URL: http://rosettacode.org/wiki/Average/Arithmetic_mean
Line 3,043:
print [mold x: [3 1 4 1 5 9] "->" average x]
print [mold x: [1000 3 1 4 1 5 9 -1000] "->" average x]
print [mold x: [1e20 3 1 4 1 5 9 -1e20] "->" average x]</
Output:
Line 3,054:
=={{header|Red}}==
Red comes with the <code>average</code> function.
<
print average []
print average [2 3 5]</
{{out}}
<pre>
Line 3,065:
The source code for <code>average</code>:
<
"Returns the average of all values in a block"
block [block! vector! paren! hash!]
Line 3,071:
if empty? block [return none]
divide sum block to float! length? block
]</
=={{header|ReScript}}==
<
let num = Js.Array.length(arr)
Line 3,081:
let mean = float_of_int(tot) /. float_of_int(num)
Js.log(Js.Float.toString(mean))</
{{out}}
<pre>
Line 3,093:
A check is made to validate if the numbers in the list are all numeric.
<
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 3,119:
if #==0 then return 'N/A: ───[no numeric values.]' /*No nums? Return N/A*/
return $ / # /*return the average. */</
'''output''' when using the (internal) lists:
<pre>
Line 3,154:
=={{header|Ring}}==
<
nums = [1,2,3,4,5,6,7,8,9,10]
sum = 0
Line 3,164:
next
return sum/len(numbers)
</syntaxhighlight>
=={{header|RPL/2}}==
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.
<
AMEAN
<< DEPTH DUP 'N' STO ->LIST ΣLIST N / >>
3.6</
=={{header|Ruby}}==
<
nums.sum(0.0) / nums.size
end
Line 3,184:
ary = nums[0,i]
puts "array size #{ary.size} : #{mean(ary)}"
end</
{{out}}
<pre>
Line 3,197:
=={{header|Run BASIC}}==
<
dim value(numArray)
for i = 1 to numArray
Line 3,207:
next
if totValue <> 0 then mean = totValue/numArray
print "The mean is: ";mean</
=={{header|Rust}}==
<
arr.iter().fold(0.0, |p,&q| p + q)
}
Line 3,224:
let w = &[];
println!("mean of {:?}: {:?}", w, mean(w));
}</
Output:
<pre>mean of [2, 3, 5, 7, 13, 21, 33, 54]: 17.25
Line 3,231:
=={{header|Sather}}==
Built to work with VEC, ("geometric" vectors), whose elements must be floats. A 0-dimension vector yields "nan".
<
mean(v:VEC):FLT is
m ::= 0.0;
Line 3,244:
#OUT + VECOPS::mean(v) + "\n";
end;
end;</
=={{header|Scala}}==
Using Scala 2.7, this has to be defined for each numeric type:
<
However, Scala 2.8 gives much more flexibility, but you still have to opt
between integral types and fractional types. For example:
<
import n._
s.foldLeft(zero)(_+_) / fromInt(s.size)
}</
This can be used with any subclass of <tt>Sequence</tt> on integral types, up
Line 3,267:
Alas, Scala 2.8 also simplifies the task in another way:
<
Here we show a function that supports fractional types. Instead of importing the definitions
Line 3,275:
=={{header|Scheme}}==
<
(if (null? l)
0
(/ (apply + l) (length l))))</
> (mean (list 3 1 4 1 5 9))
Line 3,284:
=={{header|Seed7}}==
<
include "float.s7i";
Line 3,307:
begin
writeln(mean(numVector));
end func;</
=={{header|SenseTalk}}==
SenseTalk has a built-in average function.
<
put average(empty)
</syntaxhighlight>
{{out}}
<pre>
Line 3,322:
=={{header|Sidef}}==
<
list.len > 0 || return 0;
list.sum / list.len;
Line 3,331:
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]);</
{{out}}
<pre>inf
Line 3,341:
=={{header|Slate}}==
<
[|:list| (list reduce: #+ `er ifEmpty: [0]) / (list isEmpty ifTrue: [1] ifFalse: [list size])] applyWith: {}.</
=={{header|Smalltalk}}==
<
| numbers |
Line 3,354:
(numbers inject: 0 into: [:sumSoFar :eachElement | sumSoFar + eachElement]) / numbers size ]
) displayNl.
</syntaxhighlight>
However, the empty check can be omitted, as inject returns the injected value for empty collections, and we probably do not care for the average of nothing (i.e. the division by zero exception):
<
| numbers |
numbers := #(1 2 3 4 5 6 7 8).
( numbers inject: 0 into: [:sumSoFar :eachElement | sumSoFar + eachElement]) / numbers size] ) displayNl.
</syntaxhighlight>
also, most Smalltalk's collection classes already provide sum and average methods, which makes it:
{{works with|Pharo}}
{{works with|Smalltalk/X}}
<
| numbers |
numbers := #(1 2 3 4 5 6 7 8).
(numbers sum / numbers size) displayNl.
</syntaxhighlight>
or
<
| numbers |
numbers := #(1 2 3 4 5 6 7 8).
numbers average displayNl.
</syntaxhighlight>
=={{header|SNOBOL4}}==
Line 3,385:
{{works with|CSnobol}}
<
avg i = i + 1; sum = sum + a<i> :s(avg)
avg = 1.0 * sum / prototype(a) :(return)
Line 3,398:
output = '[' str '] -> ' avg(arr)
output = '[ ] -> ' avg(empty)
end</
Output:
Line 3,406:
=={{header|SQL}}==
Tested on Oracle 11gR2, the more limited the tool, the more resourceful one becomes :)
<
create table "numbers" ("datapoint" integer);
Line 3,412:
select sum("datapoint")/count(*) from "numbers";
</syntaxhighlight>
...or...
<
=={{header|Standard ML}}==
These functions return a real:
<
| mean_reals xs = foldl op+ 0.0 xs / real (length xs);
val mean_ints = mean_reals o (map real);</
The previous code is easier to read and understand, though if you want
Line 3,432:
would rather be handled by an exception.
<
| mean_reals xs = let
val (total, length) =
Line 3,451:
in
(real total / length)
end;</
=={{header|Stata}}==
Line 3,486:
. quietly summarize population
. display r(mean)
16715.75</
=== Mean in Mata ===
<
a=11311.1\7153.8\10553.8\5707.3\
82175.7\1315.9\4724.7\10783.7
mean(a)
16715.75</
=={{header|Swift}}==
<
return s.reduce(0, +) / Double(s.count)
}
func meanInts(s: [Int]) -> Double {
return meanDoubles(s.map{Double($0)})
}</
=={{header|Tcl}}==
<
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</
=={{header|TI-83 BASIC}}==
<syntaxhighlight lang
=={{header|TI-89 BASIC}}==
<
=={{header|Trith}}==
<
[3 1 4 1 5 9] mean</
=={{header|TypeScript}}==
<
function mean(numbersArr)
{
Line 3,541:
alert( mean( [1,2,3,4,5] ) );
alert( mean( [] ) );
</syntaxhighlight>
=={{header|UNIX Shell}}==
1) First solution with bash (V >= 3), works with floats :
<
</syntaxhighlight>
<
1
2
Line 3,569:
echo "`cat f | paste -sd+ | bc -l`/`cat f | wc -l`" |bc -l
33.23134771428571428571
</syntaxhighlight>
2) This example uses <tt>expr</tt>, so it only works with integers. It checks that each string in the list is an integer.
<
if expr $# >/dev/null; then
(count=0
Line 3,596:
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</
=={{header|UnixPipes}}==
Line 3,603:
Uses [[ksh93]]-style process substitution. Also overwrites the file named <tt>count</tt> in the current directory.
{{works with|bash}}
<
b=$1;res=$2
echo "scale=5;$res+$b" | bc
Line 3,624:
}
(echo 3; echo 1; echo 4) | mean</
=={{header|Ursa}}==
<
# arithmetic mean
#
Line 3,637:
end for
out (/ (+ input) (size input)) endl console</
=={{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.
<
#import flo
Line 3,649:
#cast %e
example = mean <5.,3.,-2.,6.,-4.></
output:
<pre>1.600000e+00</pre>
=={{header|V}}==
<
[sum 0 [+] fold].
dup sum
swap size [[1 <] [1]] when /
].</
=={{header|Vala}}==
Using array to hold the numbers of the list:
<
double arithmetic(double[] list){
double mean;
Line 3,688:
stdout.printf("%s\n", mean_zero.to_string());
}
</syntaxhighlight>
Output:
Line 3,697:
=={{header|VBA}}==
<
Dim sum As Double, i As Integer
sum = 0: i = 0
Line 3,724:
Debug.Print "] = "; mean(v, leng)
Next leng
End Sub</
<pre>mean[1; 2; 2,178; 3; 3,142] = 0
mean[1; 2; 2,178; 3] = 0
Line 3,733:
=={{header|VBScript}}==
<syntaxhighlight lang=vb>
Function mean(arr)
size = UBound(arr) + 1
Line 3,745:
'Example
WScript.Echo mean(Array(3,1,4,1,5,9))
</syntaxhighlight>
{{Out}}
Line 3,752:
=={{header|Vedit macro language}}==
The numeric data is stored in current edit buffer as ASCII strings, one value per line.
<
#2 = 0 // Count
BOF
Line 3,761:
}
if (#2) { #1 /= #2 }
Num_Type(#1)</
=={{header|Vim Script}}==
Throws an exception if the list is empty.
<
if empty(a:lst)
throw "Empty"
Line 3,774:
endfor
return sum / len(a:lst)
endfunction</
=={{header|Vlang}}==
<
import arrays
Line 3,798:
println("Mean of $v.len numbers is $m\n")
}
}</
{{out}}
<pre>Vector: []
Line 3,819:
=={{header|Wart}}==
<
sum.l / len.l</
Example run:
Line 3,827:
=={{header|WDTE}}==
<
let a => import 'arrays';
Line 3,833:
a.stream nums
-> s.reduce [0; 0] (@ s p n => [+ (a.at p 0) 1; + (a.at p 1) n])
-> (@ s p => / (a.at p 1) (a.at p 0));</
This is a tad messier than it has to be due to a lack of a way to get the length of an array in WDTE currently.
Usage:
<
Output:
Line 3,844:
=={{header|Wortel}}==
<
; using a fork (sum divided-by length)
mean1 @(@sum / #)
Line 3,855:
!mean2 [3 1 4 1 5 9 2]
]]
}</
Returns:
<pre>[3.5714285714285716 3.5714285714285716]</pre>
=={{header|Wren}}==
<
static mean(arr) {
if (arr.count == 0) Fiber.abort("Length must be greater than zero")
Line 3,866:
}
}
Arithmetic.mean([1,2,3,4,5]) // 3</
=={{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>.
<
(if (= (vector-length v) 0)
nil
(let ((l (vector->list v)))
(/ (apply + l) (length l)))))</
=={{header|XPL0}}==
<
code real RlOut=48;
Line 3,893:
[Test:= [1.0, 2.0, 5.0, -5.0, 9.5, 3.14159];
RlOut(0, Mean(Test, 6)); CrLf(0);
]</
Output:
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:
<
===Runnable example===
<
<xsl:output method="text"/>
Line 3,915:
<xsl:value-of select="sum($values) div count($values)"/>
</xsl:template>
</xsl:stylesheet></
Sample input:
<
<!-- Average is 2.4 -->
<number>1</number>
Line 3,926:
<number>3</number>
<number>5</number>
</numbers></
=={{header|Yorick}}==
<
if(is_void(x)) return 0;
return x(*)(avg);
}</
=={{header|zkl}}==
Converts int to floats (implicitly):
<
mean(3,1,4,1,5,9); //-->3.83333
mean(); //-->Exception thrown: MathError(NaN (Not a number))</
To pass in a vector/list:
<
meanV(T(3,1,4,1,5,9)); // --> 3.83333</
=={{header|Zoea}}==
<
program: average
case: 1
Line 3,952:
input: [7,11]
output: 9
</syntaxhighlight>
=={{header|zonnon}}==
<
module Averages;
type
Line 3,973:
write("arithmetic mean: ");writeln(ArithmeticMean(x):10:2)
end Averages.
</syntaxhighlight>
{{out}}
<pre>
|