有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Lab 9.3问题(是的,我发现了9.1的问题)

我完成了9.1和9.2。现在,我认为答案并不是那么简单。以下是说明:

The standard deviation of a set of numbers is a measure of the spread of their values. It is defined as the square root of the average of the squared differences between each number and the mean. To calculate the standard deviation of the numbers stored in data:

Calculate the mean of the numbers.

For each number, subtract it from the mean and square the result.

Find the mean of the numbers calculated in step 2.

Find the square root of the result of step 3. This is the standard deviation. Write code to calculate the standard deviation of the numbers in data and store the result in the double sd.

To find the square root of a non-negative double d, use the expression

double s = Math.sqrt( d );

这是我的代码:

double[] data = {  }; 
double sd; 
double sum = 0; 
double mean = 0;
double sd = 0;
runProgram = true;

for (int = 0; i < data.length; i++) {
    sum += data[i];
    mean = sum/(data.length - 1);
    mean = data[i];
    mean *= mean;
}

while (runProgram == true) 
    sd += Math.sqrt(mean);

我真的不明白我做错了什么。任何建议都会尝试


共 (2) 个答案

  1. # 1 楼答案

    你把一切都搞砸了。解释似乎很好,但实现似乎出了问题。你在计算标准差的同时计算平均值,这是不对的。在计算SD之前,你需要先计算平均值,就像在你的例子中一样,平均值正在改变

    你需要正确理解这个公式

    标准偏差是SquareRoot( (sum(square(number-mean))/n) )

    // Calculate the mean first
    for (int i = 0; i < data.length; i++) {
        sum += data[i];
    }
    mean = sum / data.length;
    
    sum = 0; // Re-using sum variable
    for (int i = 0; i < data.length; i++) {
        double diff = data[i] - mean;
        diff = Math.pow(diff, 2);
        sum+=diff;
    }
    
    double variance = sum / data.length; // calculate the variance
    sd = Math.sqrt(variance); // Standard deviation is the square root of variance
    
  2. # 2 楼答案

    问题是你在计算标准偏差sd,而平均值在变化。您应该首先计算整个数据集的平均值,然后使用mean的最终值计算标准偏差

    此外,您应该只计算所有方差之和的平方根,而不是每次计算平方根