tr1, random numbers

Discussion in 'C++' started by WP, Jul 6, 2008.

  1. WP

    WP Guest

    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
    WP, Jul 6, 2008
    #1
    1. Advertising

  2. 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.
    Juha Nieminen, Jul 6, 2008
    #2
    1. Advertising

  3. WP

    WP Guest

    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!
    WP, Jul 6, 2008
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Emmanuel Deloget
    Replies:
    3
    Views:
    392
    Chris Thomasson
    Mar 3, 2007
  2. globalrev
    Replies:
    4
    Views:
    742
    Gabriel Genellina
    Apr 20, 2008
  3. Lionel B
    Replies:
    1
    Views:
    632
    Martin Eisenberg
    May 22, 2009
  4. Alex Untitled
    Replies:
    11
    Views:
    648
    Giampiero Zanchi
    Nov 16, 2009
  5. VK
    Replies:
    15
    Views:
    1,116
    Dr J R Stockton
    May 2, 2010
Loading...

Share This Page