[英]How to create an array of normal distributed random number generators in c++?
I need a series of normally distributed random numbers, with different mean and variance, I know how to create one series with a particular mean and variance but can I have like an array of generators? 我需要一系列均值和方差不同的正态分布随机数,我知道如何创建一个具有特定均值和方差的序列,但是我可以像生成器数组那样吗?
like for 1 series we have 像1系列一样
#include <random>
#include <iostream>
using namespace std;
int main()
{
random_device rd;
mt19937 gen(rd());
normal_distribution<double> d(0.0, 1.0);
for (int i = 0; i < 5000; i++)
cout << " " << d(gen) << "\n";
return 0;
}
and this gives me a series of normally distributed random numbers, and i know i can create another d with another mean and variance for another series but is there any way to have a lot of such normal_distribution d together in an array so that i can choose a particular generator by simply choosing an element in the array. 这给了我一系列正态分布的随机数,我知道我可以用另一个均值和方差为另一个序列创建另一个d,但是有什么办法可以在一个数组中有很多这样的normal_distribution d,以便我可以选择只需选择数组中的一个元素即可生成特定的生成器。
I have tried a version where 我尝试了一个版本
#include <random>
#include <iostream>
using namespace std;
int main()
{
random_device rd;
mt19937 gen(rd());
normal_distribution<double> d(0.0, 1.0),d2(0.0,1.0);
normal_distribution<double> D[]={d,d2};
for (int i = 0; i < 5000; i++)
cout << " " << D[0](gen) << "\n";
system("pause");
return 0;
}
but I want to initialize it directly with the array like D0 some thing like that so that i can put it in a loop 但是我想直接用D0之类的数组来初始化它,这样我可以将其放入循环中
Sure you can 你当然可以
#include <iostream>
#include <vector>
#include <random>
int main() {
std::vector<std::normal_distribution<double>> D{
std::normal_distribution<double>{0.0, 1.0 },
std::normal_distribution<double>{0.0, 2.0 } };
std::random_device rd;
std::mt19937 gen(rd());
std::cout << D[0](gen) << "\n";
std::cout << D[1](gen) << "\n";
return 0;
}
As you know C++ provide a functions for random numbers and we can also create and initialize array as given below. 如您所知,C ++提供了用于随机数的函数,我们还可以如下创建和初始化数组。 I hope it will helpful if not comment below. 我希望它能对下面的内容有所帮助。
const int nrolls=10000; // number of experiments
const int nstars=100; // maximum number of stars to distribute
std::default_random_engine generator;
std::normal_distribution<double> distribution(5.0,2.0);
int p[10]={};
for (int i=0; i<nrolls; ++i) {
double number = distribution(generator);
if ((number>=0.0)&&(number<10.0)) ++p[int(number)];
}
std::cout << "normal_distribution (5.0,2.0):" << std::endl;
for (int i=0; i<10; ++i) {
std::cout << i << "-" << (i+1) << ": ";
std::cout << std::string(p[i]*nstars/nrolls,'*') << std::endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.