Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C (http://www.programmingforums.org/forum60.html)
-   -   rand() isn't so random (http://www.programmingforums.org/showthread.php?t=10573)

Zap Jun 29th, 2006 2:14 PM

rand() isn't so random
 
I'm having a problem with the rand() function in the C standard library. I'm sure I'm not the first to complain about this. Every time I use this function, it generates a seemingly random number. But the number(s) is the same each time the program is ran. Is there a way around this? Or a better random number generator somewhere, that doesn't use seeds to generate random numbers? (like a generator based on the time and date)

Prm753 Jun 29th, 2006 2:20 PM

Take a look at this.

nemesis Jun 29th, 2006 2:22 PM

You need to call srand and give it a seed value which you can get from the time function
:

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

int main()
{
    long seed = time(NULL); //gets a seed from time
    srand((int)seed); //sets the seed
    for(int i = 0; i != 10; i++)
    {
          printf("%d ", rand());
    }
    return 0;
}


Zap Jun 29th, 2006 2:30 PM

I thought someone would bring this up. I've tried this. But I still get the same results each time the program is run. I read an article about rand() saying I should seed it with the time. It still yields the same results...

King Jun 29th, 2006 2:37 PM

Maybe post some code so we can have a look.

nemesis Jun 29th, 2006 2:37 PM

Well i tested my own code, and it definatly gives different results each time i run it.

Zap Jun 29th, 2006 2:42 PM

Like even this for example:

:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{

    int i;

    /* Set seed (initial seed) */
    srand( (unsigned)time( NULL ) );

    for (i = 0; i < 5; i++) {
        printf("%d\n",rand()%50);
    }

    return 0;
}


Keeps giving me:
25
10
33
16
45

nemesis Jun 29th, 2006 2:45 PM

Well i compiled you code and got 31 0 13 28 39 on the first run and 29 42 13 8 35 on the second run. So i guess it something up with your compiler, but i have no idea.

Arevos Jun 29th, 2006 3:11 PM

I got 29 32 20 20 29, then 5 32 23 28 30, so it's randomises correctly for me as well. I'm using GCC.

jim mcnamara Jun 29th, 2006 3:12 PM

Zap -

what C compiler and OS?


All times are GMT -5. The time now is 7:59 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC