英文:
How can I generate a random number with a specific distribution and primitive type in Julia?
问题
例如,生成一个具有标准正态分布的矩阵,每个数字都具有Float32类型:
rand(Normal(0,1), Float32, (2, 3))
它会引发一个MethodError错误:
MethodError: no method matching rand(::Normal{Float64}, ::Type{Float32}, ::Tuple{Int64, Int64})
但rand(Normal(0,1), (2, 3))
可以正常工作。
正确的方式是什么?
英文:
For example, generating a matrix with a standard normal distribution, every single number has the Float32 type:
rand(Normal(0,1), Float32, (2, 3))
And it throws a MethodError:
> MethodError: no method matching rand(::Normal{Float64}, ::Type{Float32}, ::Tuple{Int64, Int64})
But rand(Normal(0,1), (2, 3))
works well.
What is the correct way?
答案1
得分: 3
Assuming you are using Normal
from Distributions.jl, you just need to pass Float32
values (e.g., Float32(1)
or 1f0
) as arguments to the distribution.
julia> rand(Normal(0f0, 1f0), (2,3))
2×3 Matrix{Float32}:
0.360488 0.570298 -1.1475
-0.551529 -0.899998 0.120817
英文:
Assuming you are using Normal
from Distributions.jl, you just need to pass Float32
values (e.g., Float32(1)
or 1f0
) as arguments to the distribution.
julia> rand(Normal(0f0, 1f0), (2,3))
2×3 Matrix{Float32}:
0.360488 0.570298 -1.1475
-0.551529 -0.899998 0.120817
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论