Using any tools which you would expect to find on a nix system (in fact, if you want, msdos is also fine too), what is the easiest/fastest way to calculate the mean of a set of numbers, assuming you have them one per line in a stream or file?
views:
291answers:
6
A:
Perl.
@a = <STDIN>;
for($i = 0; $i < #@a; $i++)
{
$sum += $a[i];
}
print $a[i]/#@a;
Caveat Emptor: My syntax may be a little whiffly.
Paul Nathan
2008-10-18 01:40:44
+3
A:
perl -e 'while (<>) { $sum += $_; $count++ } print $sum / $count, "\n"';
Robert Gamble
2008-10-18 01:40:58
Interesting. I installed this on Ubuntu and I had to specify the numbers on stdin, not as arguments.
Glyph
2008-10-18 03:28:52
+5
A:
awk ' { n += $1 }; END { print n / NR }'
This accumulates the sum in n
, then divides by the number of items (NR
= Number of Records).
Works for integers or reals.
Adam Liss
2008-10-18 02:26:41
Nice on the NR trick, wasn't sure which awk answer to accept so I copped out and went for the one with the most votes!
Anthony
2008-10-18 22:00:39
+2
A:
In Powershell, it would be
get-content .\meanNumbers.txt | measure-object -average
Of course, that's the verbose syntax. If you typed it using aliases,
gc .\meanNumbers.txt | measure-object -a
Knox
2008-10-18 13:11:30