计算java中的标准差 [英] calculating standard deviation in java
本文介绍了计算java中的标准差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好
我正在尝试计算Java中的标准变体。这是一项学校任务,我已经解决了我需要的大部分工作,除了我无法获得std dev。
我知道我需要:
获取计数,计算总和,得到平均值,平方每个偏差,加上正方形并除以-1。我有很多,我似乎无法把它拉到一起。
这就是我所拥有的。
Hello
I am trying to calculate the standard variation in Java. This is a school assignment and I have worked out most of what I need except I can't get the std dev.
I know I need to:
Get the count, calculate the sum, get the average, square each deviation, add up the squares and divide by -1. I have much of that, I just can't seem to pull it together.
Here is what I have.
/**
This class is used to calculate the average and standard deviation
of a data set.
*/
public class DataSet{
private double sum;
private double sumSquare;
private int counter;
/**Constructs a DataSet object to hold the
* total number of inputs, sum and square
*/
public DataSet(){
sum = 0;
sumSquare = 0;
counter = 0;
}
/**Adds a value to this data set
* @param x the input value
*/
public void add(double x){
sum = sum + x;
sumSquare = sumSquare + x * x;
counter++;
}
/**Calculate average of dataset
* @return average, the average of the set
*/
public double getAverage(){
double avg = sum / counter;
return avg;
}
/**Get the total inputs values
* @return n, the total number of inputs
*/
public int getCount(){
return counter;
}
public double getStandardDeviation(){
}
}
推荐答案
如果通过将数据集保存在内存中并在运行中计算得不会导致性能损失,此示例可能会指向正确的方向;
If there's no performance penalty incurred by holding the data set in memory and calculating this on the fly, this example might point you in the right direction;
public class DataSet {
private final List<Double> values = new ArrayList<Double>();
public void add(final double value) {
values.add(value);
}
public double getSum() {
double sum = 0;
for(double value : values)
sum += value;
}
public double getAverage() {
if (values.size() == 0)
return 0;
return getSum() / values.size();
}
public double getPopulationStandardDeviation() {
final double average = getAverage();
double sum = 0;
for(double value : values) {
final double v = (value - average);
sum += v * v;
}
return sum;
}
public double getStandardDeviation() {
if (values.size() == 0)
return 0;
// TODO: You probably want to divide by N-1 here rather than N (where N is values.size()) if values are a random set from
// a larger population
return Math.sqrt(getPopulationStandardDeviation() / values.size());
}
}
希望这会有所帮助,
Fredrik
Hope this helps,
Fredrik
这篇关于计算java中的标准差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文