Averages/Arithmetic mean: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added Java example.)
m (Spelling/grammar/aesthetics)
Line 1: Line 1:
{{task}}
{{task}}


Write a program to find the mean (arithmetic average) of a numeric vector.
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).
The program should work on a zero-length vector (with an answer of 0).


=={{header|J}}==
=={{header|J}}==
Line 8: Line 7:
mean=: +/ % #
mean=: +/ % #


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
mean 3 1 4 1 5 9
Line 18: Line 17:
0.58243 0.402948 0.477066 0.511155
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
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.
is highly non-preferred compared to the version above.


mean1=: 3 : 0
mean1=: 3 : 0

Revision as of 22:04, 20 January 2008

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).

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

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));
...