Thread: Rand and srand

  1. #1
    Cogito Ergo Sum
    Join Date
    Mar 2007
    Location
    Sydney, Australia
    Posts
    463

    Rand and srand

    Code:
    srand ( time(NULL) );                
          i = rand () % 18;
    I need a random number chosen for every iteration of the while loop

    Code:
    while (d != 6) {
    
    srand ( time(NULL) );                
          i = rand () % 18;
    
    d++;
    }
    But the problem is, this rand and srand does it per second, so unless i put
    Code:
    d! = 10000
    , the number is always the same for 1 whole second, how can i get it to choose a random number every millisecond?

  2. #2
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    Seed the random number generator only once! See the FAQ.

  3. #3
    Captain - Lover of the C
    Join Date
    May 2005
    Posts
    341
    srand() should be called once in your entire program (preferable at the start). This seeds the random generator. I don't know that much about how it works, but I do know that the random number returned by rand() are based on the number given to srand(). If you don't seed it, your program will return the same sequence of random numbers each time you run it.
    Don't quote me on that... ...seriously

  4. #4
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    The one thing is that you're only supposed to seed the pseudo-random number generator once before use, that's just something that you're doing wrong. If you keep re-seeding, than that means you're starting the period over, meaning that you will only get a very different number when the time changes significantly enough.

    OTOH, if you fix that and then the seed itself (the time) is inappropriate because it's not random enough, you might want to try hashing the time so that you get less of a seed dependant on the clock.

    something simple like:

    h(k) = k(k + 3) % RAND_MAX

    doesn't have to be difficult, but it depends how random you need to be. If you need to be cryptographically random, you'll need to build and use a different generator than rand().

  5. #5
    abyss - deep C
    Join Date
    Oct 2007
    Posts
    46
    check out this site for info on random numbers...its from one of the C board members

    http://www.eternallyconfuzzled.com/t..._tut_rand.aspx

    cheers
    maverix

  6. #6
    Cogito Ergo Sum
    Join Date
    Mar 2007
    Location
    Sydney, Australia
    Posts
    463
    Ah yea, that fixed it, i just moved it before the loop, and it's working now, that 'hashing' citizen talked about looks interesting, thanks for that, will check it out.

    Cheers

Popular pages Recent additions subscribe to a feed