Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello,
is there a way of gettingthe average number of an array of numbers in Perl?
For example if you have:
@Array = (3, 5, 7, 12,24);
the only way to go is to declare a counter, then for each element in the array, add the element's value to the counter and then divide the counter by the number of the elements in the array, or is there a quicker way?
Thanks!

Replies are listed 'Best First'.
Re: Get average value of array of numbers
by bruno (Friar) on Oct 15, 2009 at 14:08 UTC
    use List::Util qw(sum); sub mean { return sum(@_)/@_; }

    sum returns the summation of all the elements in the array. Dividing by @_ (which in scalar context gives the number of elements) returns the average.

      Dividing by @_ (which in scalar context gives the number of elements) returns the average.
      What happens if the array is empty (0 elements)?

      Maybe:

      >perl -wMstrict -le "use List::AllUtils qw(sum); sub mean { return @_ ? sum(@_) / @_ : 0 } my @Array = (3, 5, 7, 12,24); print mean(@Array); print mean(); " 10.2 0
      Update: Per oha: What is the proper result of averaging zero elements? 0? undef? A divide-by-zero (or some other) exception? Something else? Any of these results can easily be supported. I wanted to make the point that this boundary condition should at least be considered.

      …although to be a bit more rigorous you should divide by the number of defined elements, and check to ensure that there is at least one (defined) element in the array.


      Information about American English usage here and here. Floating point issues? Please read this before posting. — emc

      Great, thanks!
Re: Get average value of array of numbers
by arun_kom (Monk) on Oct 15, 2009 at 14:38 UTC

    Probably an overkill to use a module to calculate the average, but this module also contains many other useful functions for the "mathematical formula" challenged ;)

    use Math::NumberCruncher; my @array = (3, 5, 7, 12,24); print "Average: ", Math::NumberCruncher::Mean(\@array);
Re: Get average value of array of numbers
by gulden (Monk) on Oct 15, 2009 at 14:10 UTC