如何请求boost :: normal_distribution生成不带for循环的大随机变量向量how to ask boost::normal_distribution to generate a large vector of random variables without for loop

``````for (int i=0 ; i<size ; i++){    //size is of order 1000000
boost::mt19937 gen;
gen.seed(i);
boost::normal_distribution<>  nd(0.0 , 1.0);
boost::variate_generator<boost::mt19937&, boost::normal_distribution<> >
randNormal (gen,nd);

noise = randNormal();
nsyData[i] = data[i] + sd*noise;
}
``````

1 个回复1

===============>>#1 票数：4 已采纳

``````#include <boost/random/normal_distribution.hpp>
#include <boost/random.hpp>

int main()
{
boost::mt19937 gen(42); // seed it once
boost::normal_distribution<double> nd(0.0, 1.0);
boost::variate_generator<boost::mt19937&, boost::normal_distribution<double> > randNormal(gen, nd);

std::vector<double> data(100000, 0.0), nsyData;
nsyData.reserve(data.size());

double sd = 415*randNormal();
std::transform(data.begin(), data.end(), std::back_inserter(nsyData),
[sd,&randNormal](double data) { return data + sd*randNormal(); });

}
``````

``````#include <boost/random/normal_distribution.hpp>
#include <boost/random.hpp>
#include <boost/bind.hpp>

struct Xfrm {
typedef double result_type;

template <typename Gen>
double operator()(double sd, Gen& randNormal, double data) const {
return data + sd*randNormal();
}
};

int main()
{
boost::mt19937 gen(42); // seed it once
boost::normal_distribution<double> nd(0.0, 1.0);
boost::variate_generator<boost::mt19937&, boost::normal_distribution<double> > randNormal(gen, nd);

std::vector<double> data(100000, 0.0), nsyData;
nsyData.reserve(data.size());

double sd = 415*randNormal();

std::transform(data.begin(), data.end(), std::back_inserter(nsyData),
boost::bind(Xfrm(), sd, boost::ref(randNormal), ::_1));
}
``````

1回复

1回复

1回复

2回复

1回复

1回复

1回复

1回复

2回复

1回复