简体   繁体   中英

rand() behavior not understood

I have a simple program to generate N pairs of random numbers in C.

I am using rand() for this. The value of N is a command line parameter.

I noticed that it always generates the same stream of digits when the passed command line arg is the same.

The rand() manpage says that if there is no explicit seed, the RNG is implicitly seeded by value 1 (there no call to srand() in my program).

Then however, when I call my program with arg=10 and then with arg=12, I should see the first 10 digits of both sequences as equal, right? (They will be both using the same seed, namely 1). This is not happening. It looks like the seed is being derived and applied from the arg passed implicitly, but that doesn't seem likely. Any ideas?

Update: [Sorry for not posting this earlier]

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

int main(int argc, char *argv[])  
{  
    int objs=100, i;  
    if (argc >= 2)  
        objs = atoi(argv[1]);

     for(i=0; i<objs; i++){
         int p = rand() % objs;
         int q = rand() % objs;
         printf("%d %d\n", p, q);
      }
      return 0;
}

I am using Ubuntu 12 and gcc 4.7.2.

The int version of rand will generate random numbers from 0 to RAND_MAX. Those ints will be the same with the same seed. But, there must be another step in your code which converts that number to one in the range 0-10 or 0-12. That scaling will be responsible for the different of output.

For example, if it uses division, and rand returns 25, then:

// for range 0..10,
25 / 11 => 2 (truncated)

// for range 0..12,
25 / 13 => 1 (truncated)

根据发布的代码,输出的差异似乎是由于执行随机数的模数所致。

the first 10 digits of both sequences are not equal, because rand() returns the same value (we call a) with the same seed (managed by srand() function), but statement a % objs will return different values depending on the value of objs. Notice that a % 12 mean bring a divide by 12 and get its remainder, so when %12 and %10, we will get different value.

hope this will help you

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