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+ 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.