朱莉亚:如何生成有限范围内的正态分布随机数

3

问题:在Julia中如何从高斯分布生成区间[0,1]内的随机数?

我了解randn是生成正态分布随机数的方法,但文档中关于如何指定范围的说明非常晦涩难懂。

1个回答

10

使用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)

为什么我这样做,然后尝试 std(rand(Truncated(Normal(0, 1), 0, 1), 100)),总是得到一个小于1的答案?我知道可能不会完全得到1,但我得到的结果在0.2左右,似乎比1要低得多。 - newtothis
@newtothis 你将标准正态分布限制在[0,1]范围内,这对该分布是一个相当大的限制。请注意,在[0,1]上均匀随机变量的标准差约为0.29,因此在区间[0,1]上截断的标准正态分布的结果接近该数字是合理的。通常情况下,尝试在区间[a,b]上截断标准正态分布。当ab非常接近时,标准差将接近于0,但当a趋近于负无穷,b趋近于正无穷时,标准差将趋近于1。 - Colin T Bowers

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接