[英]How to get the Standard deviation of this array
Ok so i have a code set out to get the mean of an array that has upto 50 elements, i want to also find the standard deviation of those elements and show it right under where it would display the mean, my code so far is 好的,所以我有一段代码来获取最多包含50个元素的数组的均值,我还想找到那些元素的标准差,并在显示均值的位置正确显示它,到目前为止,我的代码是
import java.util.Scanner;
public class caArray
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("How many numbers you want to calculate average upto 50 : ");
int n = input.nextInt();
int[] array = new int[50];
int sum = 0;
for (int m = 0; m < n; m++)
{
System.out.print("Number " + m + " : ");
array[m] = input.nextInt();
}
for (int m = 0; m < n; m++)
{
sum = array[m] + sum;
}
{
System.out.println("Total value of Numbers = " + sum);
}
{
double avg;
avg = sum / array.length;
System.out.println("Average of Numbers = " + avg); //calculate average value
}
}
}
i need to add into this to get the standard deviation in the one program 我需要将其添加到一个程序中以获得标准偏差
EDIT** I cannot use the functions as i actully have to use the standard deviation fourmula withing the program itself 编辑**我无法使用这些功能,因为我不得不在程序本身中使用标准偏差Fourmula
you can write it in 3 Methods 您可以用3种方法编写它
private double standardDeviation(double[] input) {
return Math.sqrt(variance(input));
}
private double variance(double[] input) {
double expectedVal = expectedValue(input);
double variance = 0;
for(int i = 0;i<input.length;++i) {
double buffer = input[i] - expectedVal;
variance += buffer * buffer;
}
return variance;
}
private double expectedValue(double[] input) {
double sum = 0;
for(int i = 0;i<input.length;++i) {
sum += input[i];
}
return sum/input.length;
}
hope it works, i am not quite shure about it, if i used the formulas the right way. 希望它能起作用,如果我以正确的方式使用公式的话,我对此并不十分了解。
But basicly you have this 3 mathematical formulas in your calculation 但基本上您的计算中有这3个数学公式
If you don't have to write it yourself, check out Apache Commons Math . 如果您不必自己编写,请查看Apache Commons Math 。 The stats documentation references how to derive standard deviations . 统计文档参考了如何得出标准差 。
As you have to write it yourself, perhaps checking out the source code for DescriptiveStatistics would be instructive (look for the function getStandardDeviation()
) 由于您必须自己编写,因此检出DescriptiveStatistics 的源代码可能是有启发性的(查找功能getStandardDeviation()
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.