如何在 Ruby 中编写不公平或有偏见的抛硬币程序?

How to program an unfair or biased coin flip in Ruby?

我需要抛硬币来遵循一定的结果概率。例如抛硬币,正面朝上的概率为 67%,反面朝上的概率为 83%,等等

我通过在等效分布中填充 100 truefalse 的数组,然后随机选择一项,设法获得了我想要的结果。更优雅的方法是什么?

Random#rand(max) (and Kernel#rand(max)):

When max is an Integer [greater than or equal to 1], rand returns a random integer greater than or equal to zero and less than max..

所以:

p = rand(100)
return p < 83  # ie. true for heads

理论上这样可以"exact"类似数组分布的方法

rand < 0.67
rand < 0.83

将分别以 67% 和 83% 的概率给出 true - 因为统一选择的随机数 x0 <= x < 1 (例如 [=16= 返回]) 将有 67% 的可能性落入细分市场 0 <= x < 0.67.