如何在 Julia 中编写任意离散分布? [英] How can I write an arbitrary discrete distribution in Julia?
问题描述
例如,以概率 0.3 返回 1.0 并以概率 0.7 返回 1.1 的分布.谢谢你.
For example, a distribution that returns 1.0 with probability 0.3 and returns 1.1 with probability 0.7. Thank you.
推荐答案
也许您不需要完整的分布类型,但只需从这样的分布中采样就足够了?
Maybe you do not need a full blown distribution type but just sampling from such a distribution is enough for you?
如果是这种情况,那么最简单的方法是:
If this is the case, then the simplest way to do it is:
using StatsBase # corrected a typo here
values = [1.0, 1.1]
probabilities = [0.3, 0.7]
w = Weights(probabilities)
sample(values, w) # sampling
如果你真的想使用一个发行版,你现在能得到的最接近的东西是:
If you actually want to use a distribution the closest thing you can get now is:
using Distributions
values = [1.0, 1.1]
probabilities = [0.3, 0.7]
d = Categorical(probabilities)
values[rand(d)] # sampling
但是会慢一点.
如果您想按照 Distributions 包类型系统定义自己的发行版,最简单的方法是使用此代码 https://github.com/JuliaStats/Distributions.jl/blob/master/src/univariate/discrete/categorical.jl 并根据修改您的需求(但我会说这将是一项重大的努力).
If you want to define your own distribution following Distributions package type system, the simplest way is to take this code https://github.com/JuliaStats/Distributions.jl/blob/master/src/univariate/discrete/categorical.jl and modify it according to your needs (but this would be a significant effort I would say).
这篇关于如何在 Julia 中编写任意离散分布?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!