Averages/Arithmetic mean: Difference between revisions

Content added Content deleted
m (F# added List.average)
m (Lang tags)
Line 3: Line 3:
=={{header|Ada}}==
=={{header|Ada}}==
This example shows how to pass a zero length vector as well as a larger vector.
This example shows how to pass a zero length vector as well as a larger vector.
with Ada.Float_Text_Io; use Ada.Float_Text_Io;
<lang ada>with Ada.Float_Text_Io; use Ada.Float_Text_Io;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO; use Ada.Text_IO;

procedure Mean_Main is
procedure Mean_Main is
type Vector is array(Positive range <>) of Float;
type Vector is array(Positive range <>) of Float;
function Mean(Item : Vector) return Float is
function Mean(Item : Vector) return Float is
Sum : Float := 0.0;
Sum : Float := 0.0;
Result : Float := 0.0;
Result : Float := 0.0;
begin
begin
for I in Item'range loop
for I in Item'range loop
Sum := Sum + Item(I);
Sum := Sum + Item(I);
end loop;
end loop;
if Item'Length > 0 then
if Item'Length > 0 then
Result := Sum / Float(Item'Length);
Result := Sum / Float(Item'Length);
end if;
end if;
return Result;
return Result;
end Mean;
end Mean;
A : Vector := (3.0, 1.0, 4.0, 1.0, 5.0, 9.0);
A : Vector := (3.0, 1.0, 4.0, 1.0, 5.0, 9.0);
begin
begin
Put(Item => Mean(A), Fore => 1, Exp => 0);
Put(Item => Mean(A), Fore => 1, Exp => 0);
New_Line;
New_Line;
-- test for zero length vector
-- test for zero length vector
Put(Item => Mean(A(1..0)), Fore => 1, Exp => 0);
Put(Item => Mean(A(1..0)), Fore => 1, Exp => 0);
New_Line;
New_Line;
end Mean_Main;
end Mean_Main;</lang>
Output:
Output:
3.83333
3.83333
Line 37: Line 37:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386 - note that some necessary LONG REAL operators are missing from ELLA's library.}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386 - note that some necessary LONG REAL operators are missing from ELLA's library.}}
<lang algol68>
<pre>
PROC mean = (REF[]REAL p)REAL:
PROC mean = (REF[]REAL p)REAL:
# Calculates the mean of qty REALs beginning at p. #
# Calculates the mean of qty REALs beginning at p. #
Line 51: Line 51:
print((mean(test),new line))
print((mean(test),new line))
)
)
</pre>
</lang>


=={{header|AmigaE}}==
=={{header|AmigaE}}==
Line 111: Line 111:
=={{header|APL}}==
=={{header|APL}}==
{{works with|APL2}}
{{works with|APL2}}
X←3 1 4 1 5 9
<lang apl> X←3 1 4 1 5 9
(+/X)÷⍴X
(+/X)÷⍴X
3.833333333
3.833333333</lang>


=={{header|BASIC}}==
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
{{works with|QuickBasic|4.5}}
Assume the numbers are in a DIM named nums.
Assume the numbers are in a DIM named nums.
mean = 0
<lang qbasic>mean = 0
sum = 0;
sum = 0;
FOR i = LBOUND(nums) TO UBOUND(nums)
FOR i = LBOUND(nums) TO UBOUND(nums)
sum = sum + nums(i);
sum = sum + nums(i);
NEXT i
NEXT i
size = UBOUND(nums) - LBOUND(nums) + 1
size = UBOUND(nums) - LBOUND(nums) + 1
PRINT "The mean is: ";
PRINT "The mean is: ";
IF size <> 0 THEN
IF size <> 0 THEN
PRINT (sum / size)
PRINT (sum / size)
ELSE
ELSE
PRINT 0
PRINT 0
END IF
END IF</lang>


=={{header|C}}==
=={{header|C}}==
Line 211: Line 211:
=={{header|Common Lisp}}==
=={{header|Common Lisp}}==


(defun mean (sequence)
<lang lisp>(defun mean (sequence)
(let ((length (length sequence)))
(let ((length (length sequence)))
(if (zerop length)
(if (zerop length)
0
0
(/ (reduce #'+ sequence) length))))
(/ (reduce #'+ sequence) length))))</lang>
=={{header|D}}==
=={{header|D}}==
Using template to make the mean function work for higher-rank array.
Using template to make the mean function work for higher-rank array.
<pre>module mean ;
<lang d>module mean ;
import std.stdio ;
import std.stdio ;


Line 246: Line 246:
writefln("array : ", array.mean()) ;
writefln("array : ", array.mean()) ;
writefln("multi : ", multi.mean()) ;
writefln("multi : ", multi.mean()) ;
}</pre>
}</lang>
=={{header|E}}==
=={{header|E}}==


Line 298: Line 298:
=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
The following computes the running mean using a tail-recursive approach. If we just sum all the values then divide by the number of values then we will suffer from overflow problems for large lists. See [http://en.wikipedia.org/wiki/Moving_average wikipedia] about the moving average computation.
The following computes the running mean using a tail-recursive approach. If we just sum all the values then divide by the number of values then we will suffer from overflow problems for large lists. See [http://en.wikipedia.org/wiki/Moving_average wikipedia] about the moving average computation.
let avg (a:float) (v:float) n =
<lang fsharp>let avg (a:float) (v:float) n =
a + (1. / ((float n) + 1.)) * (v - a)
a + (1. / ((float n) + 1.)) * (v - a)

let mean_series list =
let mean_series list =
let rec f a n list =
let rec f a n list =
match list with
match list with
| [] -> a
| [] -> a
| h :: t -> f (avg a (float h) n) (n + 1) t
| h :: t -> f (avg a (float h) n) (n + 1) t
f 0. 0 list
f 0. 0 list</lang>


Checking this:
Checking this:
Line 331: Line 331:
=={{header|Haskell}}==
=={{header|Haskell}}==
This function works if the element type is an instance of Fractional:
This function works if the element type is an instance of Fractional:
mean :: (Fractional a) => [a] -> a
<lang haskell>mean :: (Fractional a) => [a] -> a
mean [] = 0
mean [] = 0
mean xs = sum xs / Data.List.genericLength xs
mean xs = sum xs / Data.List.genericLength xs<lang>


But some types, e.g. integers, are not Fractional; the following function works for all Real types:
But some types, e.g. integers, are not Fractional; the following function works for all Real types:
meanReals :: (Real a, Fractional b) => [a] -> b
<lang haskell>meanReals :: (Real a, Fractional b) => [a] -> b
meanReals = mean . map realToFrac
meanReals = mean . map realToFrac</lang>


=={{header|IDL}}==
=={{header|IDL}}==
Line 343: Line 343:
If truly only the mean is wanted, one could use
If truly only the mean is wanted, one could use


x = [3,1,4,1,5,9]
<lang idl> x = [3,1,4,1,5,9]
print,mean(x)
print,mean(x)</lang>


But <tt>mean()</tt> is just a thin wrapper returning the zeroth element of <tt>moment()</tt> :
But <tt>mean()</tt> is just a thin wrapper returning the zeroth element of <tt>moment()</tt> :


print,moment(x)
<lang idl>print,moment(x)
; ==>
; ==>
3.83333 8.96667 0.580037 -1.25081
3.83333 8.96667 0.580037 -1.25081</lang>


which are mean, variance, skewness and kurtosis.
which are mean, variance, skewness and kurtosis.
Line 358: Line 358:
=={{header|J}}==
=={{header|J}}==


mean=: +/ % #
<lang j>mean=: +/ % #</lang>


That is, sum divided by the number of items. The verb also works on higher-ranked arrays. For example:
That is, sum divided by the number of items. The verb also works on higher-ranked arrays. For example:


mean 3 1 4 1 5 9
<lang j> mean 3 1 4 1 5 9
3.83333
3.83333
mean $0 NB. $0 is a zero-length vector
mean $0 NB. $0 is a zero-length vector
0
0
x=: 20 4 ?@$ 0 NB. a 20-by-4 table of random (0,1) numbers
x=: 20 4 ?@$ 0 NB. a 20-by-4 table of random (0,1) numbers
mean x
mean x
0.58243 0.402948 0.477066 0.511155
0.58243 0.402948 0.477066 0.511155</lang>


The computation can also be written as a loop. It is shown here for comparison only and is highly non-preferred compared to the version above.
The computation can also be written as a loop. It is shown here for comparison only and is highly non-preferred compared to the version above.


mean1=: 3 : 0
<lang j>mean1=: 3 : 0
z=. 0
z=. 0
for_i. i.#y do. z=. z+i{y end.
for_i. i.#y do. z=. z+i{y end.
z % #y
z % #y
)
)
mean1 3 1 4 1 5 9
mean1 3 1 4 1 5 9
3.83333
3.83333
mean1 $0
mean1 $0
0
0
mean1 x
mean1 x
0.58243 0.402948 0.477066 0.511155
0.58243 0.402948 0.477066 0.511155</lang>


=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|1.5+}}

Assume the numbers are in a double array called "nums".
Assume the numbers are in a double array called "nums".
<lang java5>...
...
double mean = 0;
double mean = 0;
double sum = 0;
double sum = 0;
for(double i : nums){
for(double i : nums){
sum += i;
sum += i;
}
}
System.out.println("The mean is: " + ((nums.length != 0) ? (sum / nums.length) : 0));
System.out.println("The mean is: " + ((nums.length != 0) ? (sum / nums.length) : 0));
...
...</lang>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
function mean(array) {
<lang javascript>function mean(array) {
var sum = 0;
var sum = 0;
for(var i in array)
for(var i in array)
sum += array[i];
sum += array[i];
return array.length ? sum / array.length : 0;
return array.length ? sum / array.length : 0;
}
}

alert( mean( [1,2,3,4,5] ) ); // 3
alert( mean( [1,2,3,4,5] ) ); // 3</lang>


{{libheader|Functional}}
{{libheader|Functional}}
function mean(a) {
<lang javascript>function mean(a) {
return a.length ? Functional.reduce('+', 0, a) / a.length : 0;
return a.length ? Functional.reduce('+', 0, a) / a.length : 0;
}</lang>
}


=={{header|Logo}}==
=={{header|Logo}}==
to average :l
<lang logo>to average :l
if empty? :l [output 0]
if empty? :l [output 0]
output quotient apply "sum :l count :l
output quotient apply "sum :l count :l
end
end
print average [1 2 3 4] ; 2.5
print average [1 2 3 4] ; 2.5</lang>


=={{header|Lucid}}==
=={{header|Lucid}}==

[http://en.wikipedia.org/wiki/Lucid_(programming_language)]
avg(x)
<lang lucid>avg(x)
where
where
sum = first(x) fby sum + next(x);
sum = first(x) fby sum + next(x);
n = 1 fby n + 1;
n = 1 fby n + 1;
avg = sum / n;
avg = sum / n;
end
end</lang>


=={{header|M4}}==
=={{header|M4}}==
Line 440: Line 442:


=={{header|MAXScript}}==
=={{header|MAXScript}}==
fn mean data =
<lang maxscript>fn mean data =
(
(
total = 0
total = 0
for i in data do
for i in data do
(
(
total += i
total += i
)
)
if data.count == 0 then 0 else total as float/data.count
if data.count == 0 then 0 else total as float/data.count
)
)

print (mean #(3, 1, 4, 1, 5, 9))
print (mean #(3, 1, 4, 1, 5, 9))</lang>


=={{header|Nial}}==
=={{header|Nial}}==
in the standard way, mean is
in the standard way, mean is
mean is / [sum, tally]
<lang nial>mean is / [sum, tally]


mean 6 2 4
mean 6 2 4
= 4
= 4</lang>
but it fails with 0 length vectors. so using a tally with a minimum value 1
but it fails with 0 length vectors. so using a tally with a minimum value 1


dtally is recur [ empty rest, 1 first, 1 first, plus, rest ]
<lang nial>dtally is recur [ empty rest, 1 first, 1 first, plus, rest ]
mean is / [sum, dtally]
mean is / [sum, dtally]


mean []
mean []
=0</lang>
=0


=={{header|OCaml}}==
=={{header|OCaml}}==
Line 709: Line 711:


=={{header|V}}==
=={{header|V}}==
[mean
<lang v>[mean
[sum 0 [+] fold].
[sum 0 [+] fold].
dup sum
dup sum
swap size [[1 <] [1]] when /
swap size [[1 <] [1]] when /
].</lang>
].