首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >boost::accumulators::statistics的中位数输出令人困惑

boost::accumulators::statistics的中位数输出令人困惑
EN

Stack Overflow用户
提问于 2019-03-17 15:00:33
回答 1查看 297关注 0票数 3

当我使用boost::accumulators::statistics来计算数组的中位数时,我得到了以下代码和结果:

代码语言:javascript
复制
    accumulator_set< double, features< tag::mean, tag::median > > acc;
    acc(2);
    acc(1); 
    acc(3);
    value = mean( acc );   //output is 2, expected
    value = median( acc ); //output is 3, unexpected

我认为value = median( acc )的结果应该是2。

EN

回答 1

Stack Overflow用户

发布于 2019-03-17 22:58:14

accumulator_set实际上并不存储所有的值。每次对acc(double)的调用实际上都会调用类似于acc.mean_accumulator(double); acc.median_accumulator(double)的东西,并且它尽量不存储所有的值。

对于median,使用P^2分位数估计器。(See here)这只是一个估计,如果你这样做了:

代码语言:javascript
复制
acc(4);
acc(1);
acc(2);
acc(0);
acc(3);

它返回预期的2

如果您想要一个精确值并且只有少量的数据值,请使用如下所示的函数:

代码语言:javascript
复制
#include <algorithm>
#include <vector>

// Warning: Will swap elements in the range.
// `It` needs to be a non-const random access iterator
// (Like `T*`)
template<class It>
auto median(It first, It last) {
    auto size = last - first;
    if (size % 2 == 1U) {
        std::nth_element(first, first + (size / 2U), last);
        return *(first + (size / 2U));
    }
    std::nth_element(first, first + (size / 2U), last);
    auto&& high = first + (size / 2U);
    auto&& low = std::max(first, first + (size / 2U - 1U));
    return (*low + *high) / 2;
}

// Copies the range and modifies the copy instead
template<class It>
auto const_median(It first, It last) {
    std::vector<decltype(*first)> v(first, last);
    return median(v.begin(), v.end());
}

int main() {
    std::vector<double> v{2, 1, 3};
    std::cout << median(v.begin(), v.end()) << '\n';
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55204608

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档