Binomial Distribution with Vanilla JavaScript

 JavaScript has a built-in Math.random method what gives a uniform random variable between 0 to 1(exclusive)

Suggested Reading:

What if we want to model a binomail distribution?

It's simple. We just need to set a threshhold of 0.5 that a random uniform variable is smaller that 0.5, it is 0 and, otherwise 1.

Playground

Probability of getting 1:
Sample Code
var pp = 0.5;
  var results = [];
  function flip(){
  results.push(Math.random()<pp?1:0);

  var total = 0;
  var totalsquareerror = 0
    results.forEach(x=>{
    	total+=x;     
    });
    
  var mean = total/results.length;

  results.forEach(x=>{
     totalsquareerror += (x-mn)**2; 
    });
  };

If you want a random coin flip resutle, you can use the following code

 Math.random()<p?1:0
 //p is the probability of success.

Playground

This simulator will throw a binomial random variable at every run.
n:
p:

If you want to generate a random binomial random variable using js, here is the sample code:

<script>
function getbnRandomVariable(n,p){
      var result = 0;
      for(let i =0;i<n;i++){     
          if(Math.random()<p){result++};
      }
      return result;
};
console.log(getbnRandomVariable(100,0.1));
</script>

Comments

Popular posts from this blog

How to Make A Reusable Image Slideshow HTML Component With Vanilla JavaScript

HTML Tags and Inline CSS that Work In Plotly.js Title

How to Type Spaces In HTML Input And Display In the Browser