你可以使用Julia生成一个具有特定分布和原始类型的随机数吗?

huangapple go评论51阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年7月6日 16:07:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76626751.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定