Search code examples
cdoublerandomuniform-distribution

Generating a random, uniformly distributed real number in C


I would like to generate a random, real number in the interval [0,1]. I would like to set a pointer, say n, for the number so whenever I stated n, it will be referred to the random generated number.

I have searched on StackOverflow and on Google, but most of them are for C++ or for integers.

I have tried this code suggested to me in the answers:

#include <stdio.h>
#include <stdlib.h>
int main()
{
 double n;
double get_random() { return (double)rand() / (double)RAND_MAX; }
n = get_random();
printf("%f", n);
   return 0;
}

However, I can only get a value 0.00000000.

How could I fix my program?


Solution

  • You can use:

    #include <time.h>
    srand(time(NULL)); // randomize seed
    double get_random() { return (double)rand() / (double)RAND_MAX; }
    n = get_random();
    

    srand() sets the seed which is used by rand to generate pseudo-random numbers. If you don't call srand before your first call to rand, it's as if you had called srand(1) (serves as a default).

    If you want to exclude [1] use:

    (double)rand() / (double)((unsigned)RAND_MAX + 1);
    

    Full solution:

    #include <stdio.h>
    #include <time.h>
    #include <stdlib.h>
    
    double get_random() { return ((double)rand() / (double)RAND_MAX); }
    
    int main()
    {
        double n = 0;
        srand(time(NULL)); // randomize seed
        n = get_random(); // call the function to get a different value of n every time
    
        printf("%f\n", n);  // print your number
        return 0;
    }
    

    Every time you run it you will get a different number for n.