简体   繁体   中英

Run rand() in C language and loop with Shell Scripts

I have a C code file (call " test.c " and output is " test.out ") like below and just a simple output of random number:

int main()
{
    srand(time(NULL)); 
    double r = (double)rand() / (double)RAND_MAX;
    printf("%f\n", r);
    return 0;
}

and now I use shell scripts to run " test.out " 5 times in Linux, the code below:

for i in 1 2 3 4 5
do
    test.out
done

but the result show like below

0.840188
0.840188
0.840188
0.840188
0.840188

It shows the same random number.

You initialize the pseudorandom generator using the current time. On most platforms the time function returns the current time in seconds . If you run this program multiple times in a single second then you will set the same seed in all executions, and get the same "random" number.

Add eg a sleep 1 in the loop in the script and you will see a different result.

rand() will produce the same sequence of numbers for the same seed (the one you set with srand() ).

It's very likely that your loop runs too fast and all your runs end up using the same seed (ie time(NULL) returns same value). Hence, you see the same output.

You can drand48() instead for producing uniformly distributed numbers. Or if you simply want to test rand() , you can just add a delay between your iterations.

for i in 1 2 3 4 5
do
    test.out
done

You execute the program 5 times in the same second, and since you are using system time in seconds as seed for your rand() function, naturally, you will get the same results. If you wait a second (or longer then a second) between executions, you will get different values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM