[英]what is wrong with my standard deviation calculation?
我查找标准偏差的代码是错误的。 我的代码应该从用户输入中找到标准偏差。 我输入了数字 1 2 3 并且这组数字的标准偏差是 1 但它打印了 10 我哪里出错了。 我也知道我有一堆未使用的变量,不介意它们。
import java.util.Scanner;
public class readFromKeyboard {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inStr = input.next();
int n;
int i;
int count=0;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
double average=0;
int sum;
double deviation = 0;
int total;
int temp = 0;
while (!inStr.equals("EOL")) {
count++;
n = Integer.parseInt(inStr);
min = Math.min(min, n);
max = Math.max(max, n);
System.out.printf("%d ", n);
inStr = input.next();
average += n;
temp += Math.pow(n - average, 2);
}
deviation = temp
average = average/count;
System.out.println("\n The average of these numbers is " + average);
System.out.printf("The list has %d numbers\n", count);
System.out.printf("The minimum of the list is %d\n", min);
System.out.printf("The maximum of the list is %d\n", max);
System.out.printf("The standard deviation of the list is %d\n", temp);
input.close();
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class ReadFromKeyboard {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inStr = input.next();
int n = 0;
int i;
int count = 0;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
double average = 0;
int sum;
double deviation = 0;
int total;
double temp = 0;// correction here because it must store double or float value
ArrayList<Integer> n1 = new ArrayList<Integer>();// i used this to store all entered values
while (!inStr.equals("EOL")) {
count++;
n = Integer.parseInt(inStr);
min = Math.min(min, n);
max = Math.max(max, n);
System.out.printf("%d ", n);
n1.add(n);
inStr = input.next();
average += n;
}
average = average / count; // this will give you final average
for (int j = 0; j < count; j++) {
temp += Math.pow(n1.get(j) - average, 2);
}
//System.out.println("\n" + temp + " " + count);
deviation = Math.sqrt(temp / count); // this is your standard deviation
//System.out.println(deviation);
System.out.println("\n The average of these numbers is " + average);
System.out.printf("The list has %d numbers\n", count);
System.out.printf("The minimum of the list is %d\n", min);
System.out.printf("The maximum of the list is %d\n", max);
System.out.println("The standard deviation of the list is " + deviation);
input.close();
}
}
此处定义了一个变量的标准偏差。 您必须取观测值与集合均值之间的平方差之和的均值的平方根。
//in the loop
temp += Math.pow(n - average, 2)
//outside the loop
deviation = Math.pow(temp/count,0.5) //or alternatively Math.sqrt()
这应该给你你需要的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.