Averages/Arithmetic mean: Difference between revisions

Content added Content deleted
m (→‎[[Mean#ALGOL 68]]: clarify what ELLA ALGOL 68 is missing.)
No edit summary
Line 79:
This implementation uses a plain old static array of <tt>double</tt>s for the numeric vector.
 
<lang c>#include <stdio.h>
 
double mean(double *p, unsigned qty)
Line 91:
{double test[6] = {1.0, 2.0, 5.0, -5.0, 9.5, 3.14159};
printf("%lg\n", mean(test, 6));
return 0;}</clang>
 
=={{header|C++}}==
Line 322:
These functions return a float:
 
<lang ocaml>let mean_floats xs =
if xs = [] then
0.
Line 328:
List.fold_left (+.) 0. xs /. float_of_int (List.length xs)
 
let mean_ints xs = mean_floats (List.map float_of_int xs)</ocamllang>
 
the previous code is easier to read and understand, though if you which
Line 340:
would rather be handled by an exception.
 
<lang ocaml>let mean_floats xs =
if xs = [] then
invalid_arg "empty list"
Line 363:
in
(float total /. length)
;;</ocamllang>
 
=={{header|Perl}}==
<lang perl>sub avg {
@_ or return 0;
my $sum = 0;
Line 373:
}
print avg(qw(3 1 4 1 5 9)), "\n";</perllang>
{{libheader|Data::Average}}
With module Data::Average.
(For zero-length arrays, returns the empty list.)
<lang perl>use Data::Average;
 
my $d = Data::Average->new;
$d->add($_) foreach qw(3 1 4 1 5 9);
print $d->avg, "\n";</perllang>
 
=={{header|PHP}}==
<lang php>$nums = array(3, 1, 4, 1, 5, 9);
if ($nums)
echo array_sum($nums) / count($nums), "\n";
else
echo "0\n";</phplang>
 
=={{header|Pop11}}==
Line 408:
=={{header|Python}}==
{{works with|Python|2.5}}
<lang python>def average(x):
return sum(x)/float(len(x)) if x else 0
print average([3,1,4,1,5,9])</pythonlang>
 
Output:
<lang python>3.83333333333333</pythonlang>
 
 
{{works with|Python|2.4}}
<lang python>def avg(data):
if len(data)==0:
return 0
else:
return sum(data)/float(len(data))
print avg([3,1,4,1,5,9])</pythonlang>
 
Output:
<lang python>3.83333333333333</pythonlang>
 
=={{header|Ruby}}==
<lang ruby>nums = [3, 1, 4, 1, 5, 9]
nums.empty? ? 0 : nums.inject(:+) / Float(nums.size)</rubylang>
 
=={{header|Scheme}}==
<lang scheme>(define (mean l)
(if (null? l)
0
(/ (apply + l) (length l))))</schemelang>
 
> (mean (list 3 1 4 1 5 9))