标题对我的问题非常自我解释。
我正在尝试编写一个程序来计算用户输入的一组数字的标准偏差 这比我预想的要困难得多,为它编写算法一直很痛苦 非常感谢任何帮助!
import java.util.Scanner;
public class StandardDeviation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double num;
double total;
int n;
System.out.print("First Number: ");
num = input.nextDouble();
n = 0;
total = 0;
while ( num != -1 ) {
n++;
total += num;
System.out.print("Next Number: ");
num = input.nextDouble();
}
double mean;
double dev;
double devn;
double sqrt;
mean = total/n;
dev = (total - mean);
devn = dev/n;
sqrt = Math.sqrt(devn);
System.out.println("N= " +n);
System.out.println("Total= " +total);
System.out.println("Mean= " +mean);
System.out.println("Deviation= " +dev);
System.out.print("The standard deviation is: " +sqrt);
}
}
答案 0 :(得分:3)
那是因为你的算法错了。您不能通过单独累积样本来计算标准偏差。你还必须积累他们的方格。
像这样:
n = 0;
total = 0;
total_squared = 0;
while ( num != -1 ) {
n++;
total += num;
total_squared += num*num;
System.out.print("Next Number: ");
num = input.nextDouble();
}
您的解决方案将是:
mean = total/n;
stddev = sqrt(total_squared/n - mean*mean);
答案 1 :(得分:0)
以下是使用某些样本数据计算标准偏差的方法。
double[] a = {10, 20, 30};
double total = 0;
for (double i : a) {
total += i;
}
double mean = total/a.length;
double sqTot = 0;
for (double i : a) {
sqTot += Math.pow((i-mean), 2);
}
System.out.println("Standard deviation " + Math.sqrt(sqTot/a.length));
答案 2 :(得分:0)
标准差的公式是错误的。这样做:
n = 0;
total = 0;
total_sq = 0;
while ( num != -1 ) {
n++;
total += num;
total_sq += num*num;
System.out.print("Next Number: ");
num = input.nextDouble();
}
对于人口标准差:
mean = total/n;
dev_p = sqrt(total_sq/n - mean*mean);
样本标准偏差:
dev_s = dev_p * n/(n-1);