簡體   English   中英

在java中計算標准偏差

[英]Calculating standard deviation in java

我是否在循環中計算我的標准偏差。 我知道計算標准偏差的公式,我只想知道如何獲取用戶輸入進行計算。 我是編程新手,所以請解釋一切。 我也不介意我試圖寫出標准偏差公式的抱歉嘗試,它並不是為了更多地理解 SD 而工作。

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;

    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;
      // really bad attempt here
      deviation = math.pow(n / average,2) ++ / mean sqrt(); 
    } 
    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);

    input.close(); 
  } 
}

首先你的代碼有幾個問題:

您對average使用非常令人困惑,因為您首先將其用作累加器,然后才將其除以元素數。 更好的風格是使用單獨的累加器變量來計算總和,然后在 for 循環外計算平均值。

話雖如此,一旦計算出平均值,您就可以再次遍歷您的值,並保留一個累加器變量,對於每個數字,該變量增加其與平均值之間的差值的平方,如下所示:

varianceSum += Math.pow(num - average, 2);

將所有數字相加后,您可以將varianceSum總和除以count以獲得方差(可能檢查以避免除以 0),並使用Math.sqrt()找到標准偏差。

至於從用戶那里獲取輸入,您需要為每個數字重復調用input.nextInt() 您可以讓用戶在開頭輸入輸入的數量,然后在 for 循環中遍歷它們,或者您可以使用 Scanner 的hasNext()方法讀取直到到達輸入的末尾。

你應該調用input.next(); 在循環內部重復獲取用戶輸入。

為了記錄,您可以使用in.nextInt()而不是input.next(); ,因為您在這里處理整數。 你的deviation計算不清楚。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM