我正在尝试生成具有给定float值的期望值的随机整数。以下是一些可接受的分布:
Expected value: 0.7
Random integers: 0, 1, 0, 1, 1, 1, 1, 0, 1, 1
Expected value: 0.1
Random integers: 0, 1, 0, 0, 0, 0, 0, 0, 0, 0
Expected value: 2.5
Random integers: 2, 2, 2, 3, 2, 3, 3, 3, 2, 3
答案 0 :(得分:1)
答案是在撰写问题时出现的,因此我仍将其发布以分享我的解决方案:
(Math.random() < expected_float % 1 ? 1 : 0) + Math.floor(expected_float);
该解决方案虽然没有什么特别的变化,但可以用于我的用例。
答案 1 :(得分:0)
如何解决此问题,以便您可以选择不同的数字:
var EXPECTED_VALUE = 2.7;
var RANDOM_COUNT = 10;
EXPECTED_VALUE = rando(EXPECTED_VALUE * 2, "float");//DELETE THIS LINE IF YOU WANT THE RESULT TO BE AS EXACT AS MATHEMATICALLY POSSIBLE EVERY SINGLE TIME
var randomInts = [];
var total = EXPECTED_VALUE * RANDOM_COUNT;
var totalRemainder = total % 1;
total = Math.floor(total);
for(var i = 1; i < RANDOM_COUNT; i++){
randomInts[randomInts.length] = rando(total) + (rando() < totalRemainder);
}
randomInts.sort(function(a, b){return a-b});
randomInts[randomInts.length] = total + (rando() < totalRemainder);
for(var i = randomInts.length - 1; i > 0; i--){
randomInts[i] = randomInts[i] - randomInts[i - 1];
}
此解决方案使用randojs.com使所有内容更易于阅读,因此,如果您想使用我的答案,请将其扔到html文档的head标签中:
<script src="https://randojs.com/1.0.0.js"></script>