如何在 Ruby 中获得具有给定离散分布的随机数

How to get a random number with a given discrete distribution in Ruby

我正在编写我的大学作业,它与分布和随机滚动的东西有些联系。所以问题是:如何在 Ruby.

中获得具有给定离散分布的随机数

更具体地说:在具有正态离散分布的简单示例中,例如(0,P=1/2;1000,P=1/2)我可以编写这样的函数:

 def chooseNumber(a,b)
  rval = Random.rand(0..1)
  return a if rval == 0
  return b
 end 

第一个问题:有没有办法用native Random写class?

第二个问题:处理分布的最佳方式是什么(0 与 P=1/5;2 与 P=2/5;1000 与 P=2/5)或什至更糟(0 与 P =0,33;2,P=0,49;1000,P=0,18)?

我会选择这样的东西

def pick_with_distribution(distributions)
  r = rand
  distributions.detect{ |k, d| r -= d; r < 0 }.first
end

distributions = { 0 => 0.33, 2 => 0.49, 1000 => 0.18 }
pick_with_distribution(distributions)
#=> 0

为了检查分配是否正确,我运行它10000次,结果如下:

10000.times.inject({}) do |h, _| 
  r = pick_with_distribution(distributions)
  h[r] ||= 0
  h[r] += 1
  h
end
#=> {0=>3231, 1000=>1860, 2=>4909}