Averages/Arithmetic mean

From Rosetta Code
Revision as of 12:12, 6 February 2008 by rosettacode>Spoon! (added ocaml)
Task
Averages/Arithmetic mean
You are encouraged to solve this task according to the task description, using any language you may know.

Write a program to find the mean (arithmetic average) of a numeric vector. The program should work on a zero-length vector (with an answer of 0).

Ada

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;
with Ada.Text_IO; use Ada.Text_IO;

procedure Mean_Main is
   type Vector is array(Positive range <>) of Float;
   function Mean(Item : Vector) return Float is
      Sum : Float := 0.0;
      Result : Float := 0.0;
   begin
      for I in Item'range loop
         Sum := Sum + Item(I);
      end loop;
      if Item'Length > 0 then
         Result := Sum / Float(Item'Length);
      end if;
      return Result;
   end Mean;
   A : Vector := (3.0, 1.0, 4.0, 1.0, 5.0, 9.0);
begin
   Put(Item => Mean(A), Fore => 1, Exp => 0);
   New_Line;
   -- test for zero length vector
   Put(Item => Mean(A(1..0)), Fore => 1, Exp => 0);
   New_Line;
end Mean_Main;

Output:

3.83333
0.00000

C++

double mean(std::vector<double> vNumbers)
{
     double sum = 0;
     for( std::vector<double>::iterator i = vNumbers.begin(); vNumbers.end() != i; ++i )
          sum += *i;

     if( 0 == vNumbers.size() )
          return 0;
     else
          return sum / vNumbers.size();
}

Common Lisp

This example uses a recursive sum-list function.

(defun sum-list (list)
	   (if (list)
	       (+ (car list) (sum-list (cdr list)))
	       0))
(defun mean (list)
	   (/ (sum-list list) (length list)))

J

mean=: +/ % #

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
3.83333
   mean $0         NB. $0 is a zero-length vector
0
   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.

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

Haskell

mean xs = sum xs / Data.List.genericLength xs

Java

Assume the numbers are in a double array called "nums".

...
double mean = 0;
double sum = 0;
for(double i : nums){
  sum += i;
}
System.out.println("The mean is: " + ((nums.length != 0) ? (sum / nums.length) : 0));
...

OCaml

These functions return a float:

let mean_floats xs =
  if xs = [] then
    0.
  else
    List.fold_left (+.) 0. xs /. float_of_int (List.length xs)
let mean_ints xs = mean_floats (List.map float_of_int xs)

Perl

sub avg(@_) {
  $count = 0;
  $sum = 0;
  foreach (@_) {
    $sum += $_;
    $count++;
  }
  return $count > 0 ? $sum / $count : 0;
}

print avg(qw(3 1 4 1 5 9))."\n";

Output:

3.83333333333333

With module Data::Average. (For zero-length array returns ().)

use Data::Average;

my $d = Data::Average->new;
$d->add($_) foreach (qw(3 1 4 1 5 9));
print $d->avg."\n"

Output:

3.83333333333333