是否可以将增强蓄能器与向量一起使用?
-
29-09-2019 - |
题
我想使用Boost累加器来计算一个变量的统计数据,该变量是向量。有什么简单的方法吗?我认为不可能使用最愚蠢的事情:
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);
我希望(ACC)是矢量本身,其输入[i]将是累积向量的条目的手段。
在Boost的文档中有一个暗示,但没有明确的暗示。我有点愚蠢。 :p
解决方案
我已经调查了您的问题,在我看来,BOOST.Accumulators已经提供了支持 std::vector
. 。这是我可以找到的 用户指南的一部分 :
数字运算符子图书馆很有用的另一个示例是,当一种类型未定义将其用于某些统计计算所需的运算符过载时。 例如,
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
给我一个 std::vector
尺寸2:
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);
}
我相信这是您想要的?
其他提示
我现在没有设置它可以立即尝试,但是如果所有Boost ::累加器的需求都是正确定义的数学运算符,那么您也许可以摆脱其他向量类型: http://www.boost.org/doc/libs/1_37_0/libs/numeric/ublas/doc/vector.htm
那 文档?
// 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 );