我在尝试学习 RcppParallel 时遇到问题。我尝试修改代码形式https://rcppcore.github.io/RcppParallel/用于向量求和来计算向量的平均值,看看我是否理解一般原理。
我的代码如下所示。在 c(1,2,3,4,5) 上使用函数 parallelVectorMean() 会产生不一致且最常见的错误结果。我认为这与我不了解如何正确访问开始和结束以在加入期间相应地缩放我的部分均值有关。
// [[Rcpp::depends(RcppParallel)]]
#include <RcppParallel.h>
#include <Rcpp.h>
using namespace RcppParallel;
struct Mean : public Worker
{
// source vector
const RVector<double> input;
// accumulated value
double value;
// number of elements
double num;
// constructors
Mean(const Rcpp::NumericVector input) : input(input), value(0), num(0) {}
Mean(const Mean& mean, Split) : input(mean.input), value(0), num(0) {}
// accumulate just the element of the range I've been asked to
void operator()(std::size_t begin, std::size_t end) {
num = (double) end - (double) begin;
value += (std::accumulate(input.begin() + begin, input.begin() + end, 0.0) / num);
}
// join my value with that of another Mean
void join(const Mean& rhs) {
value = (num*value + rhs.num*rhs.value)/(num + rhs.num);
num = num + rhs.num;
}
};
// [[Rcpp::export]]
double parallelVectorMean(Rcpp::NumericVector x) {
// declare the MeanBody instance
Mean mean(x);
// call parallel_reduce to start the work
RcppParallel::parallelReduce(0, x.length(), mean);
// return the computed mean
return mean.value;
}
我期待着向你们学习。