1

I need a uniformly distributed random number generator... Here is what I've tried its output is a constant number no matter how many time i run the .exe

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


int randr( int min,  int max);

int main()
{
    srand(time(NULL));
    int rr=randr(0,10);
    printf("rr=%d\n",rr)

    return 0;
}

int randr( int min,  int max)
{
    double scaled = (double)rand()/RAND_MAX;        
    return (max - min +1)*scaled + min;
}

Thanks in advance.

dragosht
  • 3,237
  • 2
  • 23
  • 32
user1740587
  • 263
  • 1
  • 2
  • 8

1 Answers1

2

The problem with your code is that the time function doesn't use milliseconds, so each call to your function set the same seed and generate the same first number (assuming it's called at the same time, i.e. the same second).

One way to avoid this is to give a seed only once in your program (srand must be called only once), you can verify that by trying this code :

int main()
{
    int a = 0;
    srand(time(NULL));
    for (int i=0;i<10000;i++){
        int rr=randr(0,10);
        a+=rr;
        printf("rr=%d\n",rr);
    }

    printf("mean : %d\n", a/10000); // to quickly check the uniformity
    return 0;
}

Another way is to use a function that can give you a different seed at each call (time based on milliseconds for example). A possible implementation on a POSIX system :

struct timespec tmp;
clock_gettime(CLOCK_MONOTONIC,&tmp);
srand(tmp.tv_nsec);

This will be based on nanoseconds (as suggested by R..), to compile you'll probably need to link with librt (-lrt on gcc).

takeo999
  • 151
  • 4