是否可以使用带向量的增压累加器?

时间:2010-11-30 17:43:18

标签: c++ templates boost accumulator

我想使用boost accumulators来计算作为向量的变量的统计信息。有一个简单的方法来做到这一点。我认为不可能使用最蠢的东西:

  using namespace boost::accumulators;
  //stuff...

  accumulator_set<vector<double>, stats<tag::mean> > acc;
  vector<double> some_vetor;
  //stuff 
  some_vector = doStuff();
  acc(some_vector);

也许这很明显,但无论如何我都试过了。 :P

我想要的是有一个累加器来计算一个向量,它是许多向量的分量的平均值。有一条简单的出路吗?

编辑:

我不知道我是否彻底清楚。我不想要这个:

 for_each(vec.begin(), vec.end(),acc); 

这将计算给定向量的条目的平均值。我需要的是不同的。我有一个会吐出矢量的函数:

 vector<double> doSomething(); 
 // this is a monte carlo simulation;

我需要多次运行并计算这些向量的向量平均值

  for(int i = 0; i < numberOfMCSteps; i++){
  vec = doSomething();
  acc(vec);
  }
  cout << mean(acc);

我希望mean(acc)是一个向量本身,其条目[i]将是累积向量的条目[i]的平均值。

在Boost的文档中提到了这一点,但没有任何明确的说法。而我有点愚蠢。 :P

3 个答案:

答案 0 :(得分:9)

我对你的问题进行了一些调查,在我看来,Boost.Accumulators已经为std::vector提供了支持。以下是我在a section of the user's guide中可以找到的内容:

  

Numeric的另一个例子   运营商子库很有用   当一个类型没有定义   使用它所需的运算符重载   用于一些统计计算。   例如,std::vector<>不会超载任何算术运算符   使用std::vector<>可能很有用   作为样本或变体类型。该   数字运算符子库定义   必要的运算符重载   boost::numeric::operators   命名空间,它被带入范围   通过累积框架与   使用指令。

事实上,经过验证后,文件boost/accumulators/numeric/functional/vector.hpp 包含了“天真”解决方案必要的运算符。

我相信你应该尝试:

  • 包括其中之一
      在任何其他累加器标题之前
    • boost/accumulators/numeric/functional/vector.hpp
    • 定义boost/accumulators/numeric/functional.hpp 时,
    • BOOST_NUMERIC_FUNCTIONAL_STD_VECTOR_SUPPORT
  • 将操作员带入using namespace boost::numeric::operators;
  • 的范围

只留下最后一个细节:执行将在运行时中断,因为初始累计值是默认构造的,并且在尝试将大小为 n 的向量添加到空向量时会发生断言。为此,您似乎应该使用(其中 n 是向量中元素的数量)初始化累加器:

accumulator_set<std::vector<double>, stats<tag::mean> > acc(std::vector<double>(n));

我尝试了以下代码,mean给了我一个大小为2的std::vector

int main()
{
    accumulator_set<std::vector<double>, stats<tag::mean> > acc(std::vector<double>(2));

    const std::vector<double> v1 = boost::assign::list_of(1.)(2.);
    const std::vector<double> v2 = boost::assign::list_of(2.)(3.);
    const std::vector<double> v3 = boost::assign::list_of(3.)(4.);
    acc(v1);
    acc(v2);
    acc(v3);

    const std::vector<double> &meanVector = mean(acc);
}

我相信这就是你想要的?

答案 1 :(得分:2)

我没有设置现在尝试,但如果所有boost :: accumulators需要正确定义的数学运算符,那么你可能能够使用不同的向量类型:http://www.boost.org/doc/libs/1_37_0/libs/numeric/ublas/doc/vector.htm < / p>

答案 2 :(得分:-3)

那么documentation呢?

// The data for which we wish to calculate statistical properties:
std::vector< double > data( /* stuff */ );

// The accumulator set which will calculate the properties for us:    
accumulator_set< double, features< tag::min, tag::mean > > acc;

// Use std::for_each to accumulate the statistical properties:
acc = std::for_each( data.begin(), data.end(), acc );