简体   繁体   中英

Can my standard deviation calculation be made more efficient?

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.

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.

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();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM