sun*_*ica 3 floating-point julia uniform-distribution
是
p = rand(-1.:eps():1., 100000)
Run Code Online (Sandbox Code Playgroud)
在 [-1, 1] 中获取随机浮点值的好方法?
一个常见的建议似乎是2. * rand(100000) - 1.相反,但是 (a) 这永远不会返回 1,因为rand的范围是[0, 1),(b) 这跳过了很多值:假设eps() == 0.1为了论证,然后rand从 (0.1, 0.2 , 0.3, ..., 0.9),并且在这个计算之后你会得到 (-0.8, -0.6, -0.4, ..., 0.8) 的结果,所以结果在范围内不再是均匀随机的。
(注意:性能方面,我在顶部的版本似乎比后一个慢 4 倍。)
在给定范围内获得均匀随机浮点数的一般推荐方法是什么?
使用 Distributions.jl 包在(-1, 1)它之间创建均匀分布并使用rand.
julia> using Distributions
julia> rand(Uniform(-1, 1), 10000)
10000-element Vector{Float64}:
0.2497721424626267
...
-0.27818099962886844
Run Code Online (Sandbox Code Playgroud)
如果您不需要向量而只需要一个标量数,您可以这样称呼它(感谢@DNF 指出这一点):
julia> rand(Uniform(-1,1))
-0.02748614119728021
Run Code Online (Sandbox Code Playgroud)
您也可以采样不同形状的矩阵/向量:
julia> rand(Uniform(-1, 1), 3, 3)
3×3 Matrix{Float64}:
-0.290787 -0.521785 0.255328
0.621928 -0.775802 -0.0569048
0.987687 0.0298955 -0.100009
Run Code Online (Sandbox Code Playgroud)
在此处查看 Distributions.jl 的文档。