Application of the Central Limit Theorem: Modeling Normal Distribution Using JavaScript

Not all programming languages come with normally distributed random variable. One useful trick is to apply the central limit theorem to model a normal distribution. 

The following simulator takes 10 random numbers from the javascript "Math.random()" method, then multiplies them by 10 and gets the average.

Suggested reading:The Central Limit Theorem Mathematical Proof or Stock Price Modeling Based on Stock Prices Following Geometric Brownian Motion

 

Sample Code for Creating A Random Normal Variable 

function getram(mean,sd,n){
    var mean = mean;
    var sd = sd;
    var n = n;
    var a = mean - Math.sqrt(n)*sd*Math.sqrt(12)/2;
    var b = mean + Math.sqrt(n)*sd*Math.sqrt(12)/2;
    var range = b - a;
    var randomvariable;
    var seeds = [];
    for(i=0;i<=n;i++){
        var x = a + Math.random()*range;
        seeds.push(x);
    };
    randomvariable = seeds.reduce(myFunc)/n;
    function myFunc(total, num) {
      return total + num;
    };
return randomvariable;
};

Z-Index Generator

We can also create a z-index then use it to get any random normal varialbes. A z-index is just simple a normal random varialbe from a normal distribution with the mean of 0 and standard deviation of 1, which is also called the standard normal distribution.

Playground

Sample Code for Creating A Random Normal Variable 

function getstandardram(){
    var mean = 0;
    var sd = 1;
    var n = 10;
    var a = mean - Math.sqrt(n)*sd*Math.sqrt(12)/2;
    var b = mean + Math.sqrt(n)*sd*Math.sqrt(12)/2;
    var range = b - a;
    var randomvariable;
    var seeds = [];
    for(i=0;i<=n;i++){
        var x = a + Math.random()*range;
        seeds.push(x);
    };
    randomvariable = seeds.reduce(myFunc)/n;
    function myFunc(total, num) {
      return total + num;
    };
return randomvariable;
};

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