How to create random variables in normal distribution with mean and standard deviation in Javascript?

Asked

Viewed 37 times

-3

I have a problem creating a variable with normal distribution in JS, I know the option math.random() is limited and that the chance of each value between 0 and 1 is equal (rectangular distribution), I saw some codes on the Internet that can transform rectangular distribution as is the case of math.random() in normal distribution. I am accepting library tips and similar for Javascript, I know that in Python it is possible to solve with a Numpy library since there is a method called np.random.normal(). There is something similar in JS?

I know that using a Box-Muller transform is possible, but I would like to optimize the code to have the mean and standard deviation as a parameter, so I could determine which standard deviation and mean I would like to use in this transformation. Can someone help me?

I’ll leave the code of the Box-Muller transform, maybe it will help to understand my problem

function random() {
    var u = 0, v = 0;
    while(u === 0) u = Math.random(); //Converting [0,1) to (0,1)
    while(v === 0) v = Math.random();
    return Math.sqrt( -2.0 * Math.log( u ) )*Math.cos( 2.0 * Math.PI * v);
}

random();
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.