基于浮点权重的随机选择
假设我有一个包含以下值的数组:
0.7523262
0.9232192
1.5824928
5.2362123
从该数组中随机选取一个值的最佳方法是什么,以便该值越高,被选择的可能性就越大?有一些常见的函数可以进行加权选择,但它们都使用 mt_rand(),这对于这样的事情不起作用。
例如,选择值 2.4652474 的可能性是选择值 1.2326237 的两倍。
Let's say I have an array with the following values:
0.7523262
0.9232192
1.5824928
5.2362123
What is the best way to randomly pick a value from this array so that the higher the value, the more likely it is to be selected? There are common functions to make a weighted selection, but they all use mt_rand(), which wouldn't work for something like this.
For example, a value of 2.4652474 would be twice as likely to be picked as a value of 1.2326237.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道这是否是最好的方法,但是您可以通过计算数组中所有条目的总和,将其乘以零到一之间的随机数以获得目标,然后计算运行总计来完成您所描述的内容对于数组中的所有条目,直到总数超过目标。返回超出目标的条目。
I don't know if it's the best way, but you can accomplish what you describe by calculating the sum of all entries in the array, multiplying that by a random number between zero and one to get the target, and then calculating a running total for all entries in the array until that total exceeds the target. Return the entry that exceeded the target.
计算
0
和整个数组之和之间的随机数。对数组进行排序,数字较小的排在前面。
从左侧开始对数组求和。当总和高于随机数时,您选择已达到的索引。
如果您有,
我们检查第一个索引。这是在
4
下面,所以我们添加第二个数字1 + 1.5 = 2.5
,它不在4
之上,所以我们添加另一个数字 < code>2.5 + 2 = 4.5 高于4
,因此我们选择第三个索引。Compute a random number between
0
and the sum of the entire array.Sort the array, so that lower numbers comes first.
Start summing up the array, from the left. When the sum is above the random number, you choose the index you have reached.
If you e.g. have
We check the first index. This is below
4
, so we would add the second number1 + 1.5 = 2.5
, this is not above4
so we add another number2.5 + 2 = 4.5
which is above4
so we choose the third index.