"Gaijinco" <ga******@gmail.com> wrote in message

news:11**********************@z14g2000cwz.googlegr oups.com...

Why is it better:

rand() / (RAND_MAX / N + 1)

than:

srand(time(0));

rand() % N;

The problem with random integers in a desired interval is that when you

start doing tricks like the above the distribution ceases to be uniform.

Here's an example revealing this problem:

#include <stdio.h>

#define MY_RAND_MAX 15 // my RAND_MAX for myrand()

#define N 10 // the N in myrand()%N

#define M 1000 // iterations count

// My fake rand() function,

// mimicking uniform distribution.

// THIS IS A BAD random generator,

// BUT A GOOD means to show the problem

// of the rand()%N approach to generate

// uniformly distributed numbers in the range

// smaller than [0,RAND_MAX].

int myrand()

{

static int seed = 0;

int res = seed;

// generate numbers in the range [0,MY_RAND_MAX]

// like so: 0,1,2,...,MY_RAND_MAX-1,MY_RAND_MAX,0,1,2,...

if (++seed > MY_RAND_MAX)

seed = 0;

return res;

}

int main()

{

int i;

int aCnt[N];

// zero up counters of each of the numbers

// that will be generated at random:

for (i=0; i<N; i++)

aCnt[i] = 0;

// generate numbers at random and count

// how many time each of them was generated:

for (i=0; i<M; i++)

aCnt[myrand()%N]++;

// print out the statistics:

printf ("Statistics:\n"

"+--------+-------------------+\n"

"| Number | Times Encountered |\n"

"+--------+-------------------+\n");

for (i=0; i<N; i++)

printf ("| %-6d | %-17d |\n", i, aCnt[i]);

printf ("+--------+-------------------+\n");

return 0;

}

Alex