Pseudorandom generator

This is a discussion on Pseudorandom generator within the C Programming forums, part of the General Programming Boards category; I got a very strange problem with rand(). Let's say I want a different sequence of random number for each ...

  1. #1
    Registered User
    Join Date
    Oct 2008
    Posts
    1

    Pseudorandom generator

    I got a very strange problem with rand(). Let's say I want a different sequence of random number for each run, I write;

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    int main()
    {
        srand((unsigned)time(NULL));
    
        int a, b;
    
        a = rand();
        b = rand();
    
        printf("a = %d\nb = %d", a, b);
    
        return 0;
    }
    For "b", everything works fine, it is truly random (or anyway: as random as this function can get). "a" behave very differently, in fact I tried this many time, and the first pseudoradom number I gererate is not random at all. In this example, I got a = 23619 the first time, then 23624, 23659, ... The more I wait, the higher it gets, as if the first random number generated was not random at all, but followed seconds.

    The best solution I found is;

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    int main()
    {
        srand((unsigned)time(NULL));
        rand();
    
        int a, b;
    
        a = rand();
        b = rand();
    
        printf("a = %d\nb = %d", a, b);
    
        return 0;
    }
    To get rid of the first "random" number. Is there a better method ?

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Code:
    srand((unsigned)time(NULL));
    The more I wait, the higher it gets, as if the first random number generated was not random at all, but followed seconds.
    This is not coincidental. You can look up Mersenne Twister if you want something "better" than plain srand(time), or maybe hash the result of time. Go to www.eternallyconfuzzled.com for more information.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pseudorandom Number Generator
    By magda3227 in forum C Programming
    Replies: 6
    Last Post: 07-17-2008, 02:16 PM
  2. Replies: 1
    Last Post: 09-04-2007, 06:31 AM
  3. NAQ: Everything you never wanted to know about CPP
    By evildave in forum C Programming
    Replies: 21
    Last Post: 12-12-2005, 10:56 AM
  4. written command line password generator
    By lepricaun in forum C Programming
    Replies: 15
    Last Post: 08-17-2004, 09:42 PM
  5. PseudoRandom Class Help??????
    By funny0ne in forum C++ Programming
    Replies: 5
    Last Post: 10-14-2002, 04:17 PM

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