简体   繁体   English

以标准偏差添加数组

[英]Adding Array in Standard Deviation

I'm doing Standard Deviation with 10 random numbers. 我正在使用10个随机数进行标准偏差。 I have to find the average of the 10 numbers. 我必须找到10个数字的平均值。 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 2,4,4,4,5,5,7,9

These eight digits have a mean (average) of 5: 这八个数字的平均值(平均值)为5:

(2 + 4 + 4 + 4 + 5 + 5 + 7 + 9) / 8 = 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 (2-5)2 = 9

( 4 - 5 )2 = 1 (4-5)2 = 1

( 4 - 5 )2 = 1 (4-5)2 = 1

( 4 - 5 )2 = 1 (4-5)2 = 1

( 5 - 5 )2 = 0 (5-5)2 = 0

( 5 - 5 )2 = 0 (5-5)2 = 0

( 7 - 5 )2 = 4 (7-5)2 = 4

( 9 - 5 )2 = 16 (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 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. 因此,与阵列2、4、4、4、5、5、7、9的标准偏差为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. 它添加了原始的10个随机数。

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. 您当前不更新数组中存储的值。

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

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