[英]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.