Can my standard deviation calculation be made more efficient?

喜欢而已 提交于 2019-12-22 10:34:23

问题


I'm curious if my standard deviation method can be made more efficient. By efficient I mean fast, and by fast I mean latency from method call to method return.

Here's the code:

public double stdDev(ArrayList<Double> input) {

    double Nrecip   = ( 1.0 / ( input.size()) );
    double sum      = 0.0;
    double average  = 0.0;

    for (Double input : inputs) {
        average += input;
    } average *= Nrecip;

    for (Double input : inputs) {
        sum += ( (input - average)*(input - average) );
    } sum *= Nrecip;

    return Math.sqrt(sum);

}

I would appreciate any advice.


回答1:


You can calculate the standard deviation in a single pass. Using a double[] would be more efficient as well.

public static double stdDev(double... a) {
    double sum = 0;
    double sq_sum = 0;
    for (int i = 0; i < n; ++i) {
        double ai = a[i];
        sum += ai;
        sq_sum += ai * ai;
    }
    double mean = sum / n;
    double variance = sq_sum / n - mean * mean;
    return Math.sqrt(variance);
}

This a conversion of this solution in C here

Passing the memory once could improve the performance.




回答2:


using org.apache.commons.math3.stat.descriptive

public double stdDev(ArrayList<Double> input) { 

    DescriptiveStatistics ds = new DescriptiveStatistics(input.toArray(new Double[0]));

    return ds.getStandardDeviation();

}


来源:https://stackoverflow.com/questions/36186103/can-my-standard-deviation-calculation-be-made-more-efficient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!