Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problems in seeding random number in c++

Tags:

c++

random

c++11

I used the following code (copied somewhere from the web) and managed to generate some an array of random numbers.

std::default_random_engine generator;
std::uniform_real_distribution<double> distribution(0,1);

int N;
std::cout<< "Please enter the number of disks to be generated: ";
std::cin>> N;

// generates N pairs of coordinates
double** R;
R = new double* [N];
for (int i=0; i<N; i++) {
    R[i] = new double [3];
    for (int j=0; j<3; j++) {
        R[i][j] = distribution(generator);
    }
}

The problem is that the output is always the same, so I think it is not seeded properly. Then I found the following code from the web, but it didn't work on my computer (I always get runtime error)

std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(1, 2);
for (int n = 0; n < 10; ++n) {
    std::cout << dis(gen) << ' ';
}
std::cout << '\n';

What's wrong with the above code? How to seed my code so I can get different outputs everytime? Besides, for the first code, is the linear congruential algorithm being used? How to use 'better' algorithm like the Mersenne Twister (mt19937) ?

thanks

like image 913
Physicist Avatar asked Mar 24 '26 05:03

Physicist


1 Answers

default_random_engine is implementation-defined. It's not specified which algo it will use.

Which runtime_error you get? It should work correct, but as workaround, you can seed mt19937 with current time as with srand.

std::mt19937 gen(static_cast<std::mt19937::result_type>(std::time(nullptr)));
like image 157
ForEveR Avatar answered Mar 28 '26 03:03

ForEveR