简体   繁体   中英

Adding Array in Standard Deviation

I'm doing Standard Deviation with 10 random numbers. I have to find the average of the 10 numbers. I then subtract the average and square it. I then have to find the average again and find the square root of the average. For example:

2, 4, 4, 4, 5, 5, 7, 9

These eight digits have a mean (average) of 5:

(2 + 4 + 4 + 4 + 5 + 5 + 7 + 9) / 8 = 5

First, calculate the difference of each element from the mean and square the results of each:

( 2 - 5 )2 = 9

( 4 - 5 )2 = 1

( 4 - 5 )2 = 1

( 4 - 5 )2 = 1

( 5 - 5 )2 = 0

( 5 - 5 )2 = 0

( 7 - 5 )2 = 4

( 9 - 5 )2 = 16

Next, calculate the mean (average) of these values and then take the square root:

Math.sqrt( (9 + 1 + 1 + 1 + 0 + 0 + 4 + 16) / 8) = 2

Thus, the standard deviation from the array 2, 4, 4, 4, 5, 5, 7, 9 is 2.

The problem I keep running into is I cant figure out how to add the numbers again the second time. It adds the original 10 random numbers.

public class StandardDeviation {
public static void main(String[] args) {
    //Create array
    int [] array = new int [10];
    //Generate 10 random numbers
    for (int i = 0; i < array.length; i++) {
        array [i] = (int)(Math.random() * 100);
        System.out.println(array[i]);
    }
    //Add 10 numbers together
    int sum = 0;
    for (int i : array) {
        sum += i;
    }
    //Find Average
    int average = sum/10;
    System.out.println("Average: " + average);
    //create New Array
    int [] variance = new int [array.length];
    for (int i = 0; i < variance.length; i++) {
        variance[i] = array[i];
    }
    //Subtract Average and Square it
    int sum2 = 0;
    for (int i: variance) {
        i -= average;
        i *= i;
        System.out.println(i);
    }
    System.out.println("Sum: " + addNumbers(variance));

}
public static int addNumbers (int [] variance) {
    int total = 0;
    for (int i = 0; i < variance.length; i++) {
    total += variance[i];
    }
    return total;
}

}

Try this for your "//Subtract Average and Square it" for loop:

for (int i = 0; i < variance.length; ++i) {
    variance[i] -= average;
    variance[i] *= variance[i];
    System.out.println(variance[i]);
}

You are not currently updating the value stored in the array.

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