Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > tr1, random numbers

Reply
Thread Tools

tr1, random numbers

 
 
WP
Guest
Posts: n/a
 
      07-06-2008
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
 
Reply With Quote
 
 
 
 
Juha Nieminen
Guest
Posts: n/a
 
      07-06-2008
WP wrote:
> 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.
 
Reply With Quote
 
 
 
 
WP
Guest
Posts: n/a
 
      07-06-2008
Juha Nieminen wrote:
> WP wrote:
>> 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.


Yes, thanks alot for the quick reply!
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
FAQ 4.10 Why aren't my random numbers random? PerlFAQ Server Perl Misc 0 04-27-2011 04:00 AM
FAQ 4.10 Why aren't my random numbers random? PerlFAQ Server Perl Misc 0 02-12-2011 11:00 PM
Math.random() and Math.round(Math.random()) and Math.floor(Math.random()*2) VK Javascript 15 05-02-2010 03:43 PM
How do I get a random number between two random numbers? Alex Untitled Ruby 11 11-16-2009 09:45 AM
random.random(), random not defined!? globalrev Python 4 04-20-2008 08:12 AM



Advertisments