Home > Blockchain >  Random sequence looks not random in c
Random sequence looks not random in c

Time:03-02

I'm implementing a basic program which generate 2 random number. The problem is the result of first number looks like it is following some kind of pattern, but the second still looks right.

Output:

6584 679
6587 1427
6591 9410
6594 156
7733 3032
7737 3780

This is my code:

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

int main(){
    srand(time(NULL));
    int a = rand()001, b= rand()001;
    printf("%d %d", a,b);

    return 0;
}

So what is the problem here and how to fix it.

Any help would be appreciated.


I am using windows 10 64 bits, gcc 8.1.0.

CodePudding user response:

time(NULL) value acts as the same seed value every time you run the program. The reason behind that your CPU will generate a similar starting NULL time for every time. To get rid of this kind of effect you need to play with the seed value, so that even if your computer starts with the same time(NULL) value, it needs to get seed different than the other runs. For that purpose, you can simply do the following:

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


int main(){
    srand((unsigned)time(NULL) * (unsigned)getpid());

    int a = rand()001, b= rand()001;
    printf("%d %d", a,b);


    return 0;
}

Full credit to @pmg, thanks for the comments to improve the solution.

  • Related