1. Overview
1.概述
The standard deviation (symbol is sigma – σ) is the measure of the spread of the data around the mean.
标准差(符号为σ-σ)是衡量数据在平均值周围的分布情况。
In this short tutorial, we’ll see how to calculate the standard deviation in Java.
在这个简短的教程中,我们将看到如何在Java中计算标准差。
2. Calculate the Standard Deviation
2.计算标准偏差
Standard deviation is computed using the formula square root of ( ∑ ( Xi – ų ) ^ 2 ) / N, where:
标准偏差的计算公式为:∑( Xi – ų ) ^ 2的平方根/ N,其中。
- ∑ is the sum of each element
- Xi is each element of the array
- ų is the mean of the elements of the array
- N is the number of elements
We can easily calculate the standard deviation with the help of Java’s Math class:
在Java的Math类的帮助下,我们可以轻松地计算出标准差。
public static double calculateStandardDeviation(double[] array) {
// get the sum of array
double sum = 0.0;
for (double i : array) {
sum += i;
}
// get the mean of array
int length = array.length;
double mean = sum / length;
// calculate the standard deviation
double standardDeviation = 0.0;
for (double num : array) {
standardDeviation += Math.pow(num - mean, 2);
}
return Math.sqrt(standardDeviation / length);
}
Let’s test our methods:
让我们测试一下我们的方法。
double[] array = {25, 5, 45, 68, 61, 46, 24, 95};
System.out.println("List of elements: " + Arrays.toString(array));
double standardDeviation = calculateStandardDeviation(array);
System.out.format("Standard Deviation = %.6f", standardDeviation);
The result will look like this:
结果会是这样的。
List of elements: [25.0, 5.0, 45.0, 68.0, 61.0, 46.0, 24.0, 95.0]
Standard Deviation = 26.732179
3. Conclusion
3.总结
In this quick tutorial, we’ve learned how to calculate the standard deviation in Java.
在这个快速教程中,我们已经学会了如何在Java中计算标准差。
As always, the example code from this article can be found over on GitHub.
一如既往,本文中的示例代码可以在GitHub上找到over。