Java程式計算標準差


在本文中,我們將瞭解如何計算標準差。標準差是衡量數字分散程度的指標。標準差的符號是西格瑪 (σ)。它是方差的平方根。

標準差 使用公式 **∑(Xi - ų)2 / N 的平方根** 計算,其中 **Xi** 是陣列的元素,**ų** 是陣列元素的平均值,**N** 是元素的數量,**∑** 是每個元素的總和。

問題陳述

給定一個 Java 程式來計算給定 陣列 數字的標準差,可以選擇手動輸入陣列值或使用預定義陣列。

輸入

Input Array : [ 35.0, 48.0, 60.0, 71.0, 80.0, 95.0, 130.0 ]

輸出

Standard Deviation: 29.313227

計算標準差的步驟

以下是計算標準差的步驟:

  • 步驟 1: 開始
  • 步驟 2: 宣告一個名為 input_array 的雙精度陣列,兩個名為 sum 和 standard_deviation 的雙精度值。
  • 步驟 3: 從使用者讀取所需的值/定義值。
  • 步驟 4: 計算 ∑(Xi - ų)2 / N 並將值儲存在 result 變數中。
  • 步驟 5: 顯示結果
  • 步驟 6: 結束

示例 1

在這裡,輸入是根據提示由使用者輸入的。

public class StandardDeviation {
   public static void main(String[] args) {
      double[] input_array = { 35, 48, 60, 71, 80, 95, 130};
      System.out.println("The elements of the array is defined as");
      for (double i : input_array) {
         System.out.print(i +" ");
      }
      double sum = 0.0, standard_deviation = 0.0;
      int array_length = input_array.length;
      for(double temp : input_array) {
         sum += temp;
      }
      double mean = sum/array_length;
      for(double temp: input_array) {
         standard_deviation += Math.pow(temp - mean, 2);
      }
      double result = Math.sqrt(standard_deviation/array_length);
      System.out.format("\n\nThe Standard Deviation is: %.6f", result);
   }
}

輸出

The elements of the array is defined as
35.0 48.0 60.0 71.0 80.0 95.0 130.0

The Standard Deviation is: 29.313227

示例 2

在這裡,我們定義了一個函式來計算標準差。

public class StandardDeviation {
public static void main(String[] args) {
      double[] input_array = { 35, 48, 60, 71, 80, 95, 130};
      System.out.println("The elements of the array is defined as");
      for (double i : input_array) {
         System.out.print(i +" ");
      }
      double standard_deviation = calculateSD(input_array);
      System.out.format("\n\nThe Standard Deviation is: %.6f", standard_deviation);
   }
   public static double calculateSD(double input_array[]) {
      double sum = 0.0, standard_deviation = 0.0;
      int array_length = input_array.length;
      for(double temp : input_array) {
         sum += temp;
      }
      double mean = sum/array_length;
      for(double temp: input_array) {
         standard_deviation += Math.pow(temp - mean, 2);
      }
      return Math.sqrt(standard_deviation/array_length);
   }
}

輸出

The elements of the array is defined as
35.0 48.0 60.0 71.0 80.0 95.0 130.0

The Standard Deviation is: 29.313227

更新於:2024年7月9日

3K+ 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告