gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 23:53:46 25 4
gpt4 key购买 nike

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

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

更新:初始值为 float

关于C++ 使用 std::accumulate 计算不正确的标准偏差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38512027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com