user3818284
user3818284

Reputation:

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

There's an existing question / answer that deals with implementing probability in JavaScript, but I've read and re-read that answer and don't understand how it works (for my purpose) or how a simpler version of probability would look.

My goal is to do:

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

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

What's the simple way to achieve this?

Upvotes: 12

Views: 13747

Answers (3)

Wax
Wax

Reputation: 625

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

Upvotes: 7

Goeast
Goeast

Reputation: 71

This is even more simple :

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

Upvotes: -1

alex
alex

Reputation: 490303

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.

Upvotes: 17

Related Questions