简体   繁体   English

编码以找到方差java

[英]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. 这是我的程序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). 我在eclipse上编码,它不仅告诉我添加return语句,而且for循环中的i ++是“死代码”(这是我第一次遇到该术语)。 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). 基本上我想做的是为一个空数组返回Double.NaN,然后​​对于其他任何数组,从平均值(for循环下的第一行)中减去位置i处的数据。 This value is then squared (second line under for loop). 然后将该值平方(for循环下的第二行)。 Since variance is the average of all these "temp" values, the return statement underneath returns temp / data.length. 由于方差是所有这些“ temp”值的平均值,因此下面的return语句返回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. 如果有人可以给我一些提示或指出正确的方向,那我就可以告诉我我做错了。

You need to move the return out of the loop statement. 您需要将return移出循环语句。

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;
}

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. 这是一个无效代码,因为如果您输入for循环,则每次都会在第一次迭代时返回一个值,因此i++语句是无用的,因为它将永远不会执行。

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; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM