有没有一种更简单的方法可以在JavaScript中实现概率函数

Is there a simpler way to implement a probability function in JavaScript?

本文关键字:JavaScript 概率函数 实现 方法 更简单 一种 有没有      更新时间:2023-09-26

有一个现有的问题/答案涉及在JavaScript中实现概率,但我已经读了一遍又一遍,不明白它是如何工作的(出于我的目的),也不明白概率的简单版本会是什么样子。

我的目标是做:

function probability(n){
    // return true / false based on probability of n / 100 
}
if(probability(70)){ // -> ~70% likely to be true
    //do something
}

实现这一点的简单方法是什么?

您可以执行以下操作。。。

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

然后用probability(.7)调用它。它之所以有效,是因为Math.random()返回了一个介于01之间(包括两者)的数字(请参见注释)。

如果必须使用70,只需在函数体中将其除以100即可。

函数概率:

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是这样的,对于一个:

  • 0%的概率(当n === 0时,它应该总是返回false):

    Math.random() < 0 // That actually will always return always false => Ok
    
  • 100%的概率(当n === 1时,应始终返回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} %`);

这更简单:

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