Below is a sample program I got to practice the use of the rand() function.
The weirdest thing is that every time the program is run, the first number generated by rand() (rand[0] in the program's output) is SIMILAR. It's not the same, but the number is always just slightly larger than the last time it was generated. rand[1-4] seem to be acceptably random however. Can anyone explain what is going on, and why??
Take a look at this sample output:
[paul@experimental C] $ ./a.out
rand[0]= 277735441 <<<??????
rand[1]= 1417591956
rand[2]= 1284424674
rand[3]= 819876274
rand[4]= 1405457966
[paul@experimental C] $ ./a.out
rand[0]= 277769055 <<<???????
rand[1]= 1982542454
rand[2]= 234757526
rand[3]= 642279943
rand[4]= 1546192179
[paul@experimental C] $ ./a.out
rand[0]= 277785862 <<<???????
rand[1]= 117534056
rand[2]= 1857407599
rand[3]= 1627223601
rand[4]= 542817462
The source code:
/*
* rand: Generates 5 numbers using standard "srand()/rand()" function
*
* SAMPLE OUTPUT:
* rand[0]= 824522256
* rand[1]= 1360907941
* rand[2]= 1513675795
* rand[3]= 1046462087
* rand[4]= 253823980
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int
main (int argc, char *argv[])
{
/* Simple "srand()" seed: just use "time()" */
unsigned int iseed = (unsigned int)time(0);
srand (iseed);
/* Now generate 5 pseudo-random numbers */
int i;
for (i=0; i<5; i++)
{
printf ("rand[%d]= %u\n",
i, rand ());
}
return 0;
}
rand
is pretty crappy and broken. My understanding is that this is for a class or something. If, some day, you really need to use pseudorandom numbers, you should try to find another library.