C++使用std::accumulate计算不正确的标准差

C++ Incorrect standard deviation calculation using std::accumulate

本文关键字:不正确 标准差 计算 accumulate 使用 std C++      更新时间:2023-10-16

我使用以下代码来计算标准偏差:

std::vector<float> k = {4,6,2};
float mean = 4;
float sum = std::accumulate(k.begin(), k.end(), 0, [&mean](float x, float y) {
    return (y - mean) * (y - mean);
});
float variance = sum / k.size();
float stdev = sqrt(variance);

std::accumulate应返回4时返回:

(4-4)^2 + (6-4)^2 + (2-4)^2 = 8

此外,打印(y - mean) * (y - mean)给出:

0
4
4

那么,为什么它不返回0 + 4 + 4呢?

您不使用x参数。尝试以下操作:

float sum = std::accumulate(k.begin(), k.end(), 0.0F, [&mean](float x, float y) {
    return x + (y - mean) * (y - mean);
});

UPDATE:初始化值为浮动