Pranav Kapoor
Pranav Kapoor

Reputation: 1281

Random Number Generator is always generating the same numbers

I am trying to fill my array with random numbers using the following piece of code

#include<iostream>
#include<random>

int main(){
int n = 5;
int list[10];
std::random_device rd;
std::mt19937 eng(rd());
std::uniform_int_distribution<> distr(0, 1000);

for(int i=0;i<n;i++)
    list[i] = distr(eng);

std::cout<<"The list of elements is: ";
for(int i=0;i<n;i++)
    std::cout<<list[i]<<" ";
}

For n = 5, I always get the same output

562 726 348 916 6

For n = 6, I always get the same output

562 726 348 916 6 594

These numbers arent random, I also checked the entropy

std:cout<<rd.entropy();

This gives me the output

0

What am I doing wrong and how do I get random numbers in my array?

Upvotes: 0

Views: 1354

Answers (2)

ComicSansMS
ComicSansMS

Reputation: 54737

Call the entropy() member function on std::random_device to find out whether your implementation implements it properly:

std::random_device may be implemented in terms of an implementation-defined pseudo-random number engine if a non-deterministic source (e.g. a hardware device) is not available to the implementation. In this case each std::random_device object may generate the same number sequence.

(Source)

If this is the case, a call to entropy() will return 0:

A deterministic random number generator (e.g. a pseudo-random engine) has entropy zero.

If that is the case, you need to use a different fallback mechanism for seeding. For instance, you could use a time-based seed like in the old C-days.

On desktop platforms in particular, you should expect std::random_device to be implemented as a proper non-deterministic source though. If this is not the case, you might just be using a very old version of the standard library implementation. If you have the feeling that the implementation should support non-deterministic std::random_device but it does not, consider filing a bug report with your standard library maintainer.

Upvotes: 3

Adrian Roman
Adrian Roman

Reputation: 531

If a random hardware device is not available to the implementation, a pseudo random number engine is used. Is a random number hardware device available? By that, I mean not only physically there, but also available to that particular implementation of std::random_device.

Upvotes: 1

Related Questions