在JavaScript中是否有一种更简单的方法来实现概率函数?

12

有一个现有的问题/答案,涉及在JavaScript中实现概率,但我已经阅读并多次阅读了那个答案,不理解它如何工作(对于我的目的)或简化版本的概率是什么样子。

我的目标是:

function probability(n){
    // return true / false based on probability of n / 100 
}

if(probability(70)){ // -> ~70% likely to be true
    //do something
}

有简单的方法来实现这个吗?

3个回答

17

你可以做类似于以下的操作...

var probability = function(n) {
     return !!n && Math.random() <= n;
};
然后使用probability(.7)进行调用。这能够行得通,因为Math.random()返回一个介于01之间的数(参见注释)。
如果你一定要使用70,只需在函数主体中将其除以100即可。

1
Math.random 的范围包括 0,因此在上面的例子中,当 random(0) 返回 true 时,可能不应该这样,所以也许应该使用 return !!n && Math.random() <= n。但是,random(1) 总是会返回 true,这很好。 - RobG
@RobG 感谢你,Rob。我总是能依赖你来填补我回答中的空白 :) - alex
1
@Alex,Math.random 返回零的情况非常罕见(因为它的范围大约是0到1.0e-15),所以可能更多是理论上的而不是实际上的。;-) - RobG

6

函数概率:

probability(n){
    return Math.random() < n;
}


// Example, for a 75% probability
if(probability(0.75)){
    // Code to run if success
}

如果我们阅读关于 Math.random() 的内容,它将返回 [0;1) 区间内的一个数字,其中包括 0 但不包括 1,为了保持均匀分布,我们需要排除上限,也就是使用 < 而不是 <=


检查上下限的概率(即为0%或100%):

我们知道 0 ≤ Math.random() < 1,因此对于 a:

  • Probability of 0% (when n === 0, it should always returning false):

    Math.random() < 0 // That actually will always return always false => Ok
    
  • Probability of 100% (when n === 1, it should always returning true):

    Math.random() < 1 // That actually will always return always true => Ok
    

运行概率函数测试

// Function Probability
function probability(n){
  return Math.random() < n;
}

// Running test with a probability of 86% (for 10 000 000 iterations)
var x = 0;
var prob = 0.86;
for(let i = 0; i < 10000000; i++){
 if(probability(prob)){
  x += 1;
 }
}
console.log(`${x} of 10000000 given results by "Math.random()" were under ${prob}`);
console.log(`Hence so, a probability of ${x / 100000} %`);


-1

这甚至更简单:

function probability(n) {
  return Math.random() <= n;
}

这是不准确的。对于 probability(0),该函数应该始终返回 false!但是如果 Math.random() 选择值 0,则您的 probability(0) 将返回 true(因为 0 <= 0)。 - Wax

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接