生成具有概率的随机整数

新手上路,请多包涵

我对如何生成具有概率的整数值感到有点困惑。

例如,我有四个整数及其概率值:1|0.4、2|0.3、3|0.2、4|0.1

考虑到它们的概率,我如何生成这四个数字?

原文由 Headshota 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 252
2 个回答

这是一个有用的技巧:-)

 function randomWithProbability() {
  var notRandomNumbers = [1, 1, 1, 1, 2, 2, 2, 3, 3, 4];
  var idx = Math.floor(Math.random() * notRandomNumbers.length);
  return notRandomNumbers[idx];
}

原文由 Sergio Tulentsev 发布,翻译遵循 CC BY-SA 3.0 许可协议

一个简单的天真方法可以是:

 function getRandom(){
  var num=Math.random();
  if(num < 0.3) return 1;  //probability 0.3
  else if(num < 0.6) return 2; // probability 0.3
  else if(num < 0.9) return 3; //probability 0.3
  else return 4;  //probability 0.1
}

原文由 bhups 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题