Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code is not finding the right variance

Tags:

java

variance

I am writing code for my AP Computer Science class and I need to find the variance of a group of numbers. For those of you who dont know how to find variance it is the sum of the squares of the differences of the values from the average all divided by 1 less then length. To make this more understandable heres an example. If you had the data {1, 5, 8, 7, 2, 7}, then the average would be 6. You variance would then be [(1-6)^2 + (5-6)^2 + (8-6)^2 + (7-6)^2 + (2-6)^2 + (7-6)^2]/5 = 8.4. So here is the method.

public static double variance(int[] data) {
    int sum = 0;
    double average;

    for (int i=0; i < data.length; i++) {
        sum = sum + data[i];
    }
    average = (double)sum/data.length;

    for (int i=0; i < data.length; i++) {
        data[i] = data[i] - (int)average^2;
    }

    int add = 0;
    for (int d : data)
        add += d;
    add = add/data.length-1;
    return add;
    }
}

I am not allowed to change data from an int array, I have no clue why I am getting the wrong variance, please help!

like image 930
user3053252 Avatar asked Aug 13 '26 10:08

user3053252


1 Answers

Your most obvious problem is here:

average^2

The ^ operator is not exponentiation. It is bitwise XOR.

Use:

Math.pow(average, 2)

or

average * average

Also,

  1. You are supposed to square the deviation, not the average.
  2. Don't do (int) cast
  3. add/data.length-1 is wrong
  4. Modifying the data array is unnecessary.

Adding in a bit of clean up,

public static double variance(int[] data) {
    int sum = 0;
    for (int datum : data) {
        sum += datum;
    } 
    double average = (double)sum / data.length;

    double devianceSum = 0;
    for (int datum : data) {
        devianceSum += Math.pow(datum - average, 2);
    }
    return devianceSum / data.length;
}
like image 135
Paul Draper Avatar answered Aug 16 '26 00:08

Paul Draper