Search code examples
rstatisticsdistributionuniform-distribution

How does "runif" function work internally in R?


I am trying to generate a set of uniformly distributed numbers in R. I know that we can use the function "runif" in R to do the same. But I really want to understand the idea behind how this function would have been developed. In the sense how does the code work for the function "runif". So, in a nutshell, I want to create my own function which can do the same task as the "runif"


Solution

  • Ultimately, runif calls a pseudorandom number generator. One of the simpler ones can be found here defined in C within the R code base and should be straightforward to emulate

    static unsigned int I1=1234, I2=5678;
    
    void set_seed(unsigned int i1, unsigned int i2)
    {
        I1 = i1; I2 = i2;
    }
    
    void get_seed(unsigned int *i1, unsigned int *i2)
    {
        *i1 = I1; *i2 = I2;
    }
    
    
    double unif_rand(void)
    {
        I1= 36969*(I1 & 0177777) + (I1>>16);
        I2= 18000*(I2 & 0177777) + (I2>>16);
        return ((I1 << 16)^(I2 & 0177777)) * 2.328306437080797e-10; /* in [0,1) */
    }
    

    So effectively this takes the initial integer seed values, shuffles them bitwise, then recasts them as double precision floating point numbers via multiplying by a small constant that normalises the doubles into the [0, 1) range.