我想知道创建概率的最佳或最可接受的方法是什么。我做了一些研究,发现在的Math.random()主题一些有趣的问题和答案,如:Math.random的概率修饰符()
How random is JavaScript's Math.random?
和
Generating random whole numbers in JavaScript in a specific range?
我在寻找一个简单的方式修改一个值将是真的概率使用Math.random()
例如,我知道Math.floor(Math.random() * 2)
是用于产生1近50%时的有用方法:
-Math.random()生成随机数0(含)之间和1(不包括)
- 如果产生的数是< 0.5,这个数字乘以2仍然会小于1,所以这个数字.floor()返回一个0如果生成的数字大于0.5,这个数字乘以2会大于1,所以这个数字.floor()返回0这个数字.floor()返回一个1
我想歪曲使用“修饰符”得到1的概率,这是clo因为我必须得到理想的概率...
每次运行代码片段时,控制台都会打印命中率。正如你所看到的,它们几乎是准确的,但并不完全。我通过反复试验提出了指数修改功能。有什么办法可以让这个更准确吗?
var youHit = Math.floor(Math.random() * 2);
var totalTries = 0;
var hits = 0;
var pointNine = 0.9; // you want 90% of tries to hit
var pointEight = 0.8;// you want 80% of tries to hit
var pointSeven = 0.7;// you want 70% of tries to hit
function probCheck(modifier) {
var exponent = 1 + (1 - modifier) + (1 - modifier)*10;
for (var x = 0; x < 100; x++) {
youHit = Math.floor((Math.pow(modifier, exponent)) + (Math.random() * 2));
totalTries += 1;
if (youHit) {
hits += 1;
}
}
console.log("final probability check: " + hits/totalTries);
};
probCheck(pointNine);
probCheck(pointEight);
probCheck(pointSeven);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
越“精确”,你就越没有随机性。 – JDB
你并没有重置全局变量'hits'和'totalTries',它们可能不应该是全局变量。 – James