简体   繁体   中英

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

#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.

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

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. 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM