Julia:生成范围受限的正态分布随机数

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?

我知道 randn 是生成正态分布随机数的方法,但是文档对如何指定范围的描述非常不透明。

使用 Distributions 包。如果您还没有:

using Pkg ; Pkg.add("Distributions")

然后:

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

或全部在一行中:

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