Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

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

Giới thiệu

Trong bài viết này, chúng ta sẽ tìm hiểu cách tính độ lệch chuẩn (standard deviation). Độ lệch chuẩn đo lường mức độ phân tán của các số. Ký hiệu là sigma (σ). Nó là căn bậc hai của phương sai.

Công thức: độ lệch chuẩn = √(Σ(Xi - μ)² / N) trong đó Xi là phần tử mảng, μ là trung bình, N là số phần tử, Σ là tổng.

Minh họa

Đầu vào:

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

Đầu ra mong muốn:

Standard Deviation: 29.313227

Thuật toán

  1. Bắt đầu
  2. Khai báo: mảng double input_array, double sum, standard_deviation
  3. Đọc giá trị từ người dùng hoặc định nghĩa trước
  4. Tính Σ(Xi - μ)² / N, lưu vào biến kết quả
  5. Hiển thị kết quả
  6. Kết thúc

Ví dụ 1: Nhập từ bàn phím

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: Tách hàm static calculateSD

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