tr1, random numbers

W

WP

Hello, I'm having some problems with the TR1 random number generators. I
need a function that takes a min and max value and generates a random
number within that range (inclusive). Here's my attempt:

int
random_number(int min, int max)
{
std::tr1::uniform_int<int>
distributor(min, max);
std::tr1::linear_congruential<unsigned long, 16807, 0, 2147483647>
generator;

generator.seed((unsigned long)time(NULL));

int n = distributor(generator);

cout << "Generated " << n << endl;

return n;
}

This function is called 50 times when the program is run with 3
different ranges and the problem is that it always returns the same
number for the same range. I am calling seed() on the generator so it's
not that. What am I doing wrong? I guess many of you won't be able to
run this code if you haven't got a very modern c++ compiler with tr1
implementation. This is my first time using tr1.

- WP
 
J

Juha Nieminen

WP said:
I am calling seed() on the generator so it's not that.

Incorrect. That's *exactly* the problem. You must *not* reseed the RNG
each time you want to get a value from it.

A RNG cannot be simply instantiated, a random value popped and then
destroyed. They don't work that way. You have to keep an instance
somewhere else, seed it only once, and then get values from it without
reseeding it.
 
W

WP

Juha said:
Incorrect. That's *exactly* the problem. You must *not* reseed the RNG
each time you want to get a value from it.

A RNG cannot be simply instantiated, a random value popped and then
destroyed. They don't work that way. You have to keep an instance
somewhere else, seed it only once, and then get values from it without
reseeding it.

Yes, thanks alot for the quick reply!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top