Alex A
Alex A

Reputation: 11

coding to find variance java

public double variance() {
    if (data.length == 0) {
        return Double.NaN;
    } else {
        for (int i = 0; i < data.length; i++) {
            double temp = average() - data[i];
            Math.pow(temp, 2);
            return temp / data.length;
        }
    }   
}

This is a snippet of code from my program, Stat. I am coding on eclipse and it tells me not only to add a return statement, but that the i++ in the for loop is "dead code" (this is the first time I am encountering that term). basically what I am trying to do is return Double.NaN for an empty array, then for any other array subtract the data at position i from the average (first line under for loop). This value is then squared (second line under for loop). Since variance is the average of all these "temp" values, the return statement underneath returns temp / data.length. I can tell I am doing this wrong, if anyone can give me a couple hints or point me in the right direction thatd be awesome.

Upvotes: 0

Views: 3987

Answers (2)

Rman
Rman

Reputation: 479

You need to move the return out of the loop statement.

public double variance() {
if (data.length == 0) {
    return Double.NaN;
} 

double variance = 0;
for (int i = 0; i < data.length; i++) {
    double temp = average() - data[i];
    variance += Math.pow(temp, 2);
}

return variance/data.length;
}

Upvotes: 1

Alexis C.
Alexis C.

Reputation: 93872

This is a dead code because if you enter in your for loop, you will return a value at the first iteration each time, and hence the statement i++ is useless because it will never be executed.

Then you else should look like this :

double temp = 0;
for (int i = 0; i < data.length; i++) {
    temp += average() - data[i];
    temp = Math.pow(temp, 2); //Math.pow returns a double so you have to assign it to temp
}
return temp/data.length; 

Upvotes: 0

Related Questions