使用概率选择数组值 [英] Picking Array Values using Probability
问题描述
给定以下概率,从黄色,蓝色和红色中选择一种随机的颜色:黄色,蓝色和红色:3/7
蓝色:1/7
红色:3/7
Pick a random color, from yellow, blue and red, given the probability of: Yellow: 3/7 Blue: 1/7 Red: 3/7
我知道我可以使用以下方法解决此问题:
[黄色,黄色,黄色,蓝色,红色,红色,红色]
但是我认为这在编程上不会很好,因为当我偶然时的可能性,我将不得不更改数组。
I know that I could work this around by using something like: [yellow, yellow, yellow, blue, red, red, red] But I don't think this would be programatically good, since when I chance the probability, I would have to change the array.
所以,我想我可以尝试类似权重法
So, I thought I could try something like a weight approach
let yellow_probability = 3/7
let blue_probability = 1/7
let red_probability = 3/7
const colors = ['yellow', 'blue', 'red']
function pickPosition(yellow_probability, blue_probability, red_probability){
let yellow_weight = Math.random() * yellow_probability
let blue_weight = Math.random() * blue_probability
let red_weight = Math.random() * red_probability
let weights = [yellow_weight, blue_weight, red_weight]
let max_of_array = Math.max.apply(Math, weights);
pickedColor = weights.indexOf(max_of_array)
return pickedColor
}
pickedColorIndex = pickPosition(yellow_probability, blue_probability, red_probability)
pickedColor = colors[pickedColorIndex]
console.log(pickedColor)
我做了一个测试:
I did a test:
let n=1000000;
let yellow=0, blue=0, red=0;
for (let i=0; i<n; i++) {
pickedColorIndex = pickPosition(yellow_probability, blue_probability, red_probability)
if (pickedColorIndex==0) yellow++
else if (pickedColorIndex==1) blue++
else red++;
}
console.log("yellow = " + yellow/n );
console.log("blue = " + blue/n );
console.log("red = " + red/n );
我希望此测试输出类似:
And I would expect this test to output something like:
Yellow = 0.43
Blue = 0.14
Red = 0.43
但是我得到:
Yellow = 0.48
Blue = 0.03
Red = 0.48
有趣的是,指出代码在概率相等时有效(1/3,1/3,1/3)或类似(1/2,1/2,0)
It is interesting to point out that the code works when the probabilities are equal (1/3, 1/3, 1/3) or something like (1/2, 1/2, 0)
任何人都可以指出我在做什么
Can anyone point out what I am doing wrong?
推荐答案
您创建了尽可能多的不同项目,而不是单个随机值,然后将其与最高价值。
Instead of a single random value, you create as many as different items you have and later take the one with the max value.
这会促进具有更高因数/概率的价值/项目。
This promotes values/items with a higher factor/probability.
您可以将一个随机值带入一个数组,然后检查随机值位于哪个间隔。接受此项。
Instead of this approach, you could take a single random value and take all probabilities into an array and check in which interval the random value is. Take this item.
编辑:代码
function getRandomIndex(probabilities) {
var random = Math.random(),
i;
for (i = 0; i < probabilities.length; i++) {
if (random < probabilities[i]) return i;
random -= probabilities[i];
}
return probabilites.length - 1;
}
var probabilities = [3 / 7, 1 / 7, 3 / 7],
j = 1e6,
count = [0, 0, 0];
while (j--) count[getRandomIndex(probabilities)]++;
console.log(count);
这篇关于使用概率选择数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!