我的标准差计算可以提高效率吗? [英] Can my standard deviation calculation be made more efficient?

查看:145
本文介绍了我的标准差计算可以提高效率吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇我的标准差方法是否可以提高效率. 高效"是指快速,而快速"是指从方法调用到方法返回的等待时间.

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.

这是代码:

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.

推荐答案

您可以通过一次计算标准偏差.使用double[]也会更有效.

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

此解决方案的转换在C语言中

传递一次内存可以提高性能.

Passing the memory once could improve the performance.

这篇关于我的标准差计算可以提高效率吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆