Computer >> Máy Tính >  >> Lập trình >> Java

Chương trình Java để tính độ lệch chuẩn

Trong bài này, chúng ta sẽ hiểu cách tính độ lệch chuẩn. Độ lệch chuẩn là thước đo mức độ dàn trải của các con số. Biểu tượng của nó là sigma (σ). Nó là căn bậc hai của phương sai.

Độ lệch chuẩn được tính bằng công thức căn bậc hai của ∑ (Xi - ų) 2 / N trong đó Xi là phần tử của mảng, ų là giá trị trung bình của các phần tử của mảng, N là số phần tử, ∑ là tổng của từng phần tử.

Dưới đây là một minh chứng về điều tương tự -

Giả sử đầu vào của chúng tôi là -

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

Đầu ra mong muốn sẽ là -

Standard Deviation: 29.313227

Thuật toán

Step 1 - START
Step 2 – Declare a double array namely input_array, two doube values namely sum and standard_deviation.
Step 3 - Read the required values from the user/ define the values.
Step 4 – Compute ∑(Xi - ų)2 / N and store the value in result variable.
Step 5 - Display the result
Step 6 - Stop

Ví dụ 1

Tại đây, đầu vào đang được người dùng nhập dựa trên lời nhắc.

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);
   }
}

Đầu ra

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

Ví dụ 2

Ở đây, chúng tôi đã xác định một hàm để tính toán độ lệch chuẩn.

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);
   }
}

Đầu ra

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