Thread: rand() weirdness

  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
    28,413
    You may want to read Prelude's article on Using rand(), in particular the section on seeding the PRNG.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    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,005
    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