Results 1 to 3 of 3

Thread: Generating random Numbers c++

  1. #1
    Join Date
    Oct 2008
    Beans
    68

    Generating random Numbers c++

    Hi guys I am trying to generate 150 numbers in less than 2 seconds.


    Code:
    srand(time(NULL));
    opt=rand()%4+1;
    QString mes=get_Character(opt);
    But it is giving me the same numbers
    I was reading about drand48_r(3) but still I don't get it.Can some one help in this?

    Thanks

  2. #2
    Join Date
    Aug 2007
    Location
    Novocastria, Australia
    Beans
    751
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Re: Generating random Numbers c++

    Are you calling this snippit 150 times? If that is the case, then you could be seeding to the exact same number each time (if the code runs very quickly, which I'm sure it would).

    I would suggest seeding only once then just taking 150 numbers with rand().

  3. #3
    Join Date
    Sep 2007
    Location
    Christchurch, New Zealand
    Beans
    1,328
    Distro
    Ubuntu

    Re: Generating random Numbers c++

    Yes as NovaAesa says.
    you see srand is a "pseudo random" number generator and while the numbers it produces don't appear to be connected, it is always part of the same and identical sequence. This is often desirable so that it will produce repeatable results.

    The reason you use the time function to "seed" the sequence is to start that sequence off in an unpredictable place, but when you seed it again, you may just be resetting it to that same start position

    p.s. I just googled it for you and it says: "The rand() function shall compute a sequence of pseudo-random integers in the range [0, {RAND_MAX}] with a period of at least 2**32.
    Last edited by worksofcraft; September 29th, 2010 at 05:06 AM.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •