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

You could do something like...

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

Then call it with probability(.7). It works because Math.random() returns a number between and inclusive of 0 and 1 (see comment).

If you must use 70, simply divide it over 100 in the body of your function.


Function Probability:

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


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

If we read about Math.random(), it will return a number in the [0;1) interval, which includes 0 but exclude 1, so to keep an even distribution, we need to exclude the top limit, that to say, using < and not <=.


Checking the upper and the lower bound probability (which are 0% or 100%):

We know that 0 ≤ Math.random() < 1 so, for 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
    

Running test of the probability function

// 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} %`);

Tags:

Javascript