felipX
felipX

Reputation: 21

Repeated initial sequence of random generator

I need to gen pseudo-random numbers in the 0 : 23 range. I'm trying this:

#include <iostream>
#include <cstdlib>
#include <random>
#include <ctime>


std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(0,23);

unsigned int random;

random = distribution(generator);

My problem is: Everytime I run my program, the first three random numbers is 0 , 3 , 18.

How can I solve this, and why this happens ?

Upvotes: 0

Views: 60

Answers (1)

Remember the P stands for "pseudo"!

A PRNG takes a seed to start generation of a pseudo random number sequence from. Since you don't provide it yourself, std::default_random_engine uses the same seed when default constructed. So you get the same sequence every time.

One possible and easy way to seed it, is to employ a std::random_device as a source for a little entropy:

std::random_device r;
std::default_random_engine generator(r());

If possible, r will produce a non-deterministic number. Otherwise, it too will be PRNG, so you aren't worse off. It's not the best scheme, but it should get you started.

Upvotes: 2

Related Questions