Real Random number generator: Uniform distribution


'uniform_dist' is a function written in language C which takes as input two real (double) numbers which represent a range, and return a real (double) value according to a Uniform distribution within the given range .
The range doesn't include low and high (we will see this later).

        #include <stdlib.h>
        #include <time.h> //necessary for time_t variable
        #include <stdio.h>     

        double uniform_dist(double low, double high) {
             return ( (double)rand() / RAND_MAX) * (high - low) + low;
       }


      #define NUM 100;
       int   main(int argc, char* argv[]) {
              time_t t;
              srand((unsigned int)time(&t));
              double low = 1.5, high = 4.5;

              for (int i=0; i < NUM; ++i) {
                 printf("%f\n", uniform_dist(low, high) );
              }

        return 0;
       }


  • int rand(void) returns a random integer number in the range [0, RAND_MAX]
  • The value of RAND_MAX is library-dependent. It is an integer and is at least 32767.
  • As we want to return a double number the cast to double through '(double)' is necessary. 
  • srand() should be initialized with different number for each run. The variable 't' is actually different for each run. In this way rand() will generate a different set of number every time we launch this program.
As you can see launching this program, the upper limit 4.5 is never generated but  some returned numbers are quite close to it:

# ./a.out > out.dat

# cat out.dat | grep ^4\.499
4.499968
4.499012
4.499012



# cat out.dat | grep ^1\.501
1.501015
1.501344
1.501905
1.501532


So we can say that we have "nearly" generated the range [1.5, 4.5]

Question: can we generate the numbers 1.5 and 4.5 ?

Commenti

Post popolari in questo blog

Real random number generator: a basic gaussian distribution