Search code examples
randomrangejulianormal-distribution

Julia: Generate normally distributed random number with restricted range


Question: How can I generate a random number in the interval [0,1] from a Gaussian distribution in Julia?

I gather randn is the way to generate normally distributed random numbers, but the documentation's description of how to specify a range is quite opaque.


Solution

  • Use the Distributions package. If you don't already have it:

    using Pkg ; Pkg.add("Distributions")
    

    then:

    using Distributions
    mu = 0    #The mean of the truncated Normal
    sigma = 1 #The standard deviation of the truncated Normal
    lb = 0    #The truncation lower bound
    ub = 1    #The truncation upper bound
    d = Truncated(Normal(mu, sigma), lb, ub)  #Construct the distribution type
    x = rand(d, 100) #Simulate 100 obs from the truncated Normal
    

    or all in one line:

    x = rand(Truncated(Normal(0, 1), 0, 1), 100)