如何用Ruby程序不公平或偏见抛硬币吗? - How to program an unfair or biased coin flip in Ruby?

- 此内容更新于:2016-02-01
主题:

我需要做一个抛硬币,服从一定概率的结果。例如,抛硬币出来正面的概率67%,83%的机会出来反面,等我拿到结果后,填充数组与100和等效分布,然后随机选择一个条目。什么是更好的路要走呢?

原文:

I need to make a coin flip that obeys a certain probability of outcome. For example, a coin flip with a 67% chance of coming out Heads, 83% chance of coming out Tails, etc.

I managed to get the result I'm after by populating an array with 100 true and false in the equivalent distribution, then picking one item at random. What is a more elegant way to go about it?

网友:问的时候,我们预计两件事之一:最小的例子代码演示这个问题,或者一个列表的地方你搜索和一个解释为什么这些没有帮助你解决这个问题。阅读“如何问”和“最小的、完整的和可核查的例子”。你的问题使它看起来像你想让我们编写代码解决这个问题,这不是什么是堆栈溢出。相反,我们来帮助您解决问题,纠正你的错误。请告诉我们您的代码。

(原文:When asking, we expect one of two things: A minimal example of your code demonstrating the problem, or a list of the places you searched and an explanation why those didn't help you solve the problem. Read "How to Ask" and "Minimal, Complete, and Verifiable example". Your question makes it look like you want us to write code solving the problem, which is not what Stack Overflow is for. Instead we're here to help you solve the problem by correcting your mistakes. Please show us your code.)

解决方案:
(和):当马克斯是一个整数(大于等于1),兰德返回一个随机整数大于或等于零,小于最大..所以:理论上这样可以像数组一样“精确”分布的方法。
原文:

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..

So:

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

In theory such can be "exact" like an array distribution method.

楼主:当然,我应该想到这一点!谢谢!

(原文:Of course, I should have thought of that! Thanks!)

解决方案:
将概率分别为67%和83%——因为一个统一选择随机数(如返回的)将67%可能土地段。
原文:
rand < 0.67
rand < 0.83

will give true with probability of 67% and 83%, respectively - because a uniformly selected random number x that is 0 <= x < 1 (such as returned by Kernel#rand) will be 67% likely to land in the segment 0 <= x < 0.67.

楼主:我将不得不接受其他海报的答案,因为他会先给基本上相同的答案,但这是非常优雅!我现在觉得自己愚蠢。

(原文:I'm going to have to accept the other poster's answer because he gave basically the same answer first, but that's very elegant indeed! I feel stupid now.)

网友:不相同:你可以用这种方法做任意的概率(例如)。

(原文:Not quite same: you can do arbitrary probabilities with this approach (e.g. rand < 0.12834).)

网友:应该是第二种情况呢?

(原文:Should it be rand < 0.17 for the second case?)

网友:@sagarpandya82:我不是处理正面或反面,只是概率。如果你想要特定代码,我想这将是和…显然,这可能被写在其他方面。

(原文:@sagarpandya82: I am not dealing with heads or tails, just with probabilities. If you want specific code, I guess it would be rand < 0.67 ? :heads : :tails and rand < 0.83 ? :tails : :heads... which could, obviously, be written in other ways, too.)