2

我正在将方程转换为 C++。这对于运行标准偏差是否正确。

this->runningStandardDeviation = (this->sumOfProcessedSquaredSamples - sumSquaredDividedBySampleCount) / (sampleCount - 1);

这是完整的功能:

void BM_Functions::standardDeviationForRunningSamples (float samples [], int sampleCount)
{
    // update the running process samples count
    this->totalSamplesProcessed += sampleCount;

    // get the mean of the samples
    double mean = meanForSamples(samples, sampleCount);

    // sum the deviations
   // sum the squared deviations
   for (int i = 0; i < sampleCount; i++)
   {
        // update the deviation sum of processed samples
        double deviation = samples[i] - mean;
        this->sumOfProcessedSamples += deviation;

        // update the squared deviations sum
        double deviationSquared = deviation * deviation;
        this->sumOfProcessedSquaredSamples += deviationSquared;
    }

    // get the sum squared
    double sumSquared = this->sumOfProcessedSamples * this->sumOfProcessedSamples;

    // get the sum/N
    double sumSquaredDividedBySampleCount = sumSquared / this->totalSamplesProcessed;

    this->runningStandardDeviation = sqrt((this->sumOfProcessedSquaredSamples -     sumSquaredDividedBySampleCount) / (sampleCount - 1));
}
4

2 回答 2

12

用于计算运行均值和方差/SD 的数值稳定且有效的算法是 Welford 算法

一种 C++ 实现是:

std::pair<double,double> getMeanVariance(const std::vector<double>& vec) {
    double mean = 0, M2 = 0, variance = 0;

    size_t n = vec.size();
    for(size_t i = 0; i < n; ++i) {
        double delta = vec[i] - mean;
        mean += delta / (i + 1);
        M2 += delta * (vec[i] - mean);
        variance = M2 / (i + 1);
        if (i >= 2) {
            // <-- You can use the running mean and variance here 
        }
    }

    return std::make_pair(mean, variance);
}

注意:要获得 SD,只需取sqrt(variance)

于 2013-06-11T20:19:00.497 回答
1

您可以检查是否有足够的 sampleSount(1 会导致除以零)

确保变量具有合适的数据类型(浮点)

否则这看起来是正确的......

于 2013-06-11T19:56:03.827 回答