rand() weirdness

This is a discussion on rand() weirdness within the C++ Programming forums, part of the General Programming Boards category; So, I'm debugging a bit of code that should work, but my computer hates me. What am I doing wrong? ...

  1. #1
    Registered User
    Join Date
    Aug 2006
    Posts
    43

    rand() weirdness

    So, I'm debugging a bit of code that should work, but my computer hates me. What am I doing wrong?

    In my main() function, I've got the simplest of loops:

    Code:
    for(int z = 0; z < nGenerations; z++)
        ParseData(nGridWidth, nGridHeight, dScore, gridInfo);
    Then, a bit further along, I've got the offending function:

    Code:
    int ParseData(int nGridWidth, int nGridHeight, double dScore[], vector <vector <sGrid> >& gridInfo)
    {
        int nCrossPoint;
    
        srand((unsigned)time(NULL));
    
        for(int j = 0; j < rand() % 25 + 1; j++)
        {
            rand();
        }
        
        for(int i = 0; i < nGridWidth / 2; i++)
        {
            nCrossPoint = rand() % nNumGenes;
            cout << nCrossPoint << endl;
        }
    
        return 0;
    }
    Here's the problem: The first time the function ParseData() is called, everything seems to be working fine. I get a set of (pseudo)random numbers that are good enough for my purposes. However, every subsequent call to the function gives me the same sequence of numbers. I could call the thing 10,000 times, and still get the same results. What's up with that?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,739
    You may want to read Prelude's article on Using rand(), in particular the section on seeding the PRNG.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    http://c-faq.com/lib/srand.html
    Note also that it's rarely useful to call srand more than once during a run of a program; in particular, don't try calling srand before each call to rand, in an attempt to get ``really random'' numbers.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  4. #4
    Registered User
    Join Date
    Aug 2006
    Posts
    43

    It's all so clear to me now.

    Thank you both for your prompt replies. I always enjoy a bit of good late-night reading.

    This is one of those situations when you know it's time to turn off the computer and pack it in for the night. Of course it was doing what it was doing...

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21