# Can anyone explain this code to me? Calculation of mean and variance.

• March 24th, 2013, 12:24 PM
hemla
Can anyone explain this code to me? Calculation of mean and variance.
Code Java:

```public class MeanVariance { public static void main (String[] args) { int len = args.length; double[] data = new double[len]; double mean, sum = 0, sum2 = 0, var;   for (int i = 0; i < len; i++) { data[i] = Double.parseDouble(args[i]); }   for (int i = 0; i < len; i++) { sum += data[i]; } mean = sum / len; System.out.println(mean);   for (int i = 0; i < len; i++) { sum2 += Math.pow((data[i] - mean),2); } var = sum2 / len; System.out.println(var); } }```

I really don't understand this code which is used to calculate the mean and variance from a data set.
• March 24th, 2013, 12:33 PM
Norm
Re: Can anyone explain this code to me? Calculation of mean and variance.
Have you looked up the algorithms with google so you know what the code is supposed to do?

Which statements in the code are you having problems with?
• March 24th, 2013, 12:45 PM
hemla
Re: Can anyone explain this code to me? Calculation of mean and variance.
Yes, i've looked up into that and the code is supposed to calculate the mean and variance and print it out on two separate lines. The mean of N data items is calculated by adding up all the items and dividing the total by N. Variance is defined as the average of the squared distance between each item and the mean. I have problems understanding arrays so it would really help if you explain the code from scratch. :)
• March 24th, 2013, 12:47 PM
Norm
Re: Can anyone explain this code to me? Calculation of mean and variance.
Quote:

I have problems understanding arrays so it would really help if you explain the code from scratch.
Start with the tutorial: Arrays (The Java™ Tutorials > Learning the Java Language > Language Basics)

If there are any specific statements you don't understand, post the code and ask your questions about them.
• March 24th, 2013, 04:02 PM
hemla
Re: Can anyone explain this code to me? Calculation of mean and variance.
Code Java:

`double mean, sum = 0, sum2 = 0, var;`

What does the above line mean?
• March 24th, 2013, 04:17 PM
Norm
Re: Can anyone explain this code to me? Calculation of mean and variance.
It defines 4 variables of type double and assigns values to two of them.