Is there an easier way to implement probability functions in JavaScript?

There is an existing question / answer regarding the implementation of probability in JavaScript, but I read and re-read this answer and don’t understand how it works (for my purpose) or what a simpler version of probability looks like.

My goal:

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

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

What is an easy way to achieve this?

+4
source share
2 answers

You can do something like ...

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

Then call him probability(.7). It works because it Math.random()returns a number between and inclusively 0and 1(see Comment).

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

+5

:

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

All Articles