【问题标题】:Using boost::accumulators::statistics to find median of an array使用 boost::accumulators::statistics 查找数组的中位数
【发布时间】:2018-03-12 17:17:53
【问题描述】:

我有一个在 MATLAB 中计算的大尺寸一维数组。我需要找到这个数组的中位数。我想为此目的使用 boost c++ 库,因为它具有使用 P-square 算法计算中位数的实现,该算法对于大型数组有效。下面是一个一个推入 5 个数字并使用 boost 库找到中位数的代码。我想更改此代码,以便可以将数组作为参数传递并找到该数组的中位数。数组的大小很大,所以我不能使用“for循环”来推送累加器集中的每个元素。

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>
#include <iostream>

using namespace boost::accumulators;

int main() {   
 accumulator_set<double, features<tag::mean, tag::median> > acc;  

 acc(8);   
 acc(9);   
 acc(10);   
 acc(11);   
 acc(12);   
 //double arr[3] = {1,2,3};   
 //acc(arr);   
 std::cout << mean(acc) << '\n';   
 std::cout << median(acc) << '\n'; 
}

我确实找到了一些要求使用向量的资源,但我不明白。一个工作示例,其中一个小数组作为参数传递,然后使用 boost c++ 库找到中位数将受到高度赞赏。

【问题讨论】:

    标签: c++ arrays boost


    【解决方案1】:

    简单地迭代:

    for (auto d : arr)
        acc(d);
    

    或者使用算法:

    for_each(begin(arr), end(arr), ref(acc));
    

    注意:使用std::ref(acc) 避免传值!

    演示

    Live On Coliru

    #include <boost/accumulators/accumulators.hpp>
    #include <boost/accumulators/statistics.hpp>
    #include <iostream>
    
    using namespace boost::accumulators;
    
    int main() {
        accumulator_set<double, features<tag::mean, tag::median> > acc;
    
        double arr[3] = { 1, 2, 3 };
    
        for (auto d : arr)
            acc(d);
    
        using namespace std;
        for_each(begin(arr), end(arr), ref(acc));
    
        std::cout << mean(acc) << '\n';
        std::cout << median(acc) << '\n';
    }
    

    PS:

    如果你坚持要有功能接口:

    Live On Coliru

    template <typename Accum, typename Range>
    void do_sample(Accum& accum, Range const& range) {
        using namespace std;
        for_each(begin(range), end(range), std::ref(accum));
    }
    

    (也适用于向量或任何其他范围)。打印:

    2
    3
    

    【讨论】:

    • 添加了更多解释和一个带有函数调用接口的版本:do_sample
    • @ChrisChiasson 好问题,是的,这就是你在更大系列中得到的(统计上的)。 Boost Accumulators 适用于具有采样但没有完整内存数据集的 大型 数据集。为此,他们implement the median in terms of the single quantile estimation with the P² algorithm
    • 这是一个经典的精度/内存权衡。如果您不需要它,只需对数组进行排序并选择中间即可。如果您需要它,很高兴您可以采样千兆字节并且仍然可以获得可靠的结果,而无需在大型机器上等待很长时间:)
    猜你喜欢
    • 2019-08-07
    • 2013-09-22
    • 2015-04-15
    • 2017-11-11
    • 2014-02-24
    • 2013-09-17
    • 2013-08-08
    • 1970-01-01
    • 2019-12-12
    相关资源
    最近更新 更多