根据加权百分比机会计算价值
我正在编写一个程序,其中我需要根据加权机会获得一个随机值,并且遇到了真正的困难。我需要做的一个例子:
a = 50%,b = 30%,c = 10%,d = 10%
在这个例子中,我需要能够获得一个随机值,a、b、c 或 d ,返回的值在 50% 的情况下为“a”,在 30% 的情况下为 b,等等...
非常感谢
I am writing a program in which I need to get a random value based on weighted chances and am having real difficulty. An example of what I need to do:
a = 50%, b = 30%, c = 10%, d = 10%
In this example, I need to be able to get a random value, a,b,c or d, with the value coming back being as 'a' 50% of the time, b 30% of the time, etc...
Many thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据每个值出现的机会,为每个值分配一个介于 0 和 1 之间的数字。例如,A 应该是 0 到 0.5,因为它需要 50% 的机会。然后,获取一个0到1之间的随机数。随机数落入哪个值的范围就是您获得的值。
A = [0, .5)
B = [.5, .8)
C = [.8, .9)
D = [.9, 1)
随机数为 [0,1)
[ = 包含,) = 排除。
Assign each value a range of numbers between 0 and 1 based on the chance it should appear. For example, A should be 0 to .5, since it needs a 50% chance. Then, get a random number between 0 and 1. Whichever value's range the random number falls into is the value you get.
A = [0, .5)
B = [.5, .8)
C = [.8, .9)
D = [.9, 1)
Random number is [0,1)
[ = inclusive, ) = exclusive.