...

# Generating a random number taken from a normal distribution

ac11ca
01-25-2012, 04:32 PM
Hello,

I need help creating a function in javascript that produces random numbers generated from a normal curve distribution with a mean and standard deviation that I can specify (and easily change). I would like only whole numbers and the ability to set reasonable maximum and minimums.

Thanks,

Philip M
01-25-2012, 06:36 PM
<script type = "text/javascript">

function rnd_snd() {
return (Math.random()*2-1)+(Math.random()*2-1)+(Math.random()*2-1);
}

// Three random numbers between -1 and 1 added together. That will give a normal distribution with mean = 0 and standard deviation = 1.
// The function will return a decimal with an average value of 0.

function rnd(mean, stdev) {
return Math.round(rnd_snd()*stdev + mean);
}

// Multiply the result by the standard deviation that you want, then add your desired mean.

alert (rnd(38,2)) // mean, standard deviation

</script>

All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.

Dormilich
01-26-2012, 05:06 PM
// Three random numbers between -1 and 1 added together. That will give a normal distribution with mean = 0 and standard deviation = 1.
// The function will return a decimal with an average value of 0.

out of interest, do you have any detailed info about that statement?

Philip M
01-26-2012, 08:26 PM
out of interest, do you have any detailed info about that statement?

Not quite sure what you mean, but all I have done here is added three random numbers between -1 and 1 together. That will give a point (almost +3 to almost -3) on a normal distribution with mean = 0 and standard deviation = 1. This is also called standard normal distribution. Try it yourself:-

<script type = "text/javascript">

var tot = 0;
var its = 500; // iterations
for (var i = 0; i<its; i++) {
var randy = (Math.random()*2-1)+(Math.random()*2-1)+(Math.random()*2-1);
tot += randy;
document.write(randy);
document.write("<br>")
}

alert (tot/its); // close to zero, especially if the number of iterations is increased to (say) 10000

</script>

Dormilich
01-26-2012, 11:08 PM

thanks, that was the bit of info I wanted.

ac11ca
02-03-2012, 10:43 PM
Thank you! Very useful, and I will have a play around with it soon.

Now things get a little more tricky: What about a chi square distribution (with 3 degrees of freedom)?

Cheers,

Philip M
02-04-2012, 08:32 AM
Now things get a little more tricky: What about a chi square distribution (with 3 degrees of freedom)?