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!
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,
(int) castadd/data.length-1 is wrongdata 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With