简体   繁体   中英

returning infinity in my for loop?

Right now when I run my code it returns infinity in the std dev and variance. How do I fix this?

When I take the //VARIANCE and //STD DEV out of the for loop it gives me a value but it's not the right one. So I'm thinking it's because when you take it out of the for loop "i" isn't working correctly? I know "i" is the problem because it's supposed to be "for the number of elements in the number list, take each element and subtract the average and square it." How do I achieve it?

@Override
public String calculate() throws Exception {
    //String firstConfidenceInterval = String.valueOf(SRC_Calc_Type.CI(PH, CV, N));
    double total = 0.0;
    double total1 = 0.0;
    int i;
    String delims = ",";
    String[] tokens = nums.split(delims);

    for(i = 0; i < tokens.length; i++) {
        total += (Double.parseDouble(tokens[i]));// SUM
    }
    double average = total / i; //average
    total1 += (Math.pow((i - average), 2) / i); //VARIANCE
    double std_dev = Math.pow(total1, 0.5); //STDDEV

    return String.valueOf("Sum: " + total + //Works
            "\nMean: " + average + //Works
            "\nStandard Deviation: " + std_dev + //works
            "\nVariance: " + total1); //works
    //"\nNumbers Sorted: " + "( " +  " )"
}

Replace i with tokens.length() everywhere outside the loop. In the futute, to avoid errors like this, always initialize variables when you declare them, and always declare them in the narrowest scope. fot(int I=0 ... in this case. Note, that your formula for variance is wrong. This is not how you computer variance.

You need a second loop to calculate the variance

double variance=0;
for(String token : tokens) {
  double value = Double.parseDouble(token);
  variance += Math.pow(value-average,2);
}
variance = variance/tokens.length;

You are misunderstanding how to calculate the variance and the standard deviation. You don't subtract the average from the number of elements.

You need to calculate the differences of each individual sample from the mean, square them all, then add all of the squares.

double variance = 0.0;
for (i = 0; i < tokens.length; i++)
{
    // It would be better to parse the tokens once and
    // place them into an array; they are referenced twice.
    double diff = Double.parseDouble(tokens[i]) - average;
    variance += diff * diff;
}
// of (tokens.length - 1) for "sample" variance
variance /= tokens.length;

Then you can take the square root for the standard deviation.

double std_dev = Math.sqrt(variance);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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