mk_
mk_

Reputation: 417

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.

Upvotes: 1

Views: 237

Answers (3)

c633
c633

Reputation: 556

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 % objswill 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

Upvotes: 0

nathan-m
nathan-m

Reputation: 8865

based on the code posted, it appears the difference in output is due to the modulus of the random number being performed.

Upvotes: 1

Douglas
Douglas

Reputation: 37761

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)

Upvotes: 6

Related Questions