Last active
December 15, 2015 05:19
-
-
Save jbowles/5207749 to your computer and use it in GitHub Desktop.
Random numbers from a normal distribution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*jslint node:true*/ | |
"use strict"; | |
function normal_random(mean, variance) { | |
if (mean === undefined) { | |
mean = 0.0; | |
} | |
if (variance === undefined) { | |
variance = 1.0; | |
} | |
var V1, V2, S; | |
do { | |
var U1 = Math.random(); | |
var U2 = Math.random(); | |
V1 = 2 * U1 -1; | |
V2 = 2 * U2 -1; | |
S = V1 * V1 + V2 * V2; | |
} while (S > 1); | |
var X = 0; | |
var Z = 0; | |
X = Math.sqrt(-2 * Math.log(S) / S) * V1; | |
//Y = Math.sqrt(-2 * Math.log(S) / S) * V2; | |
Z = mean + Math.sqrt(variance) * X; | |
//Y = mean + Math.sqrt(variance) * Y; | |
return Z; | |
} | |
var i = 0; | |
var limit = 10000000; | |
//node normal_random.js 0.60s user 0.01s system 100% cpu 0.613 total | |
//var limit = 100000000; | |
//node normal_random.js 5.68s user 0.03s system 100% cpu 5.683 total | |
//var limit = 1000; | |
while (i < limit){ | |
//console.log(normal_random(100,100)); | |
var rq = normal_random(100,100); | |
//normal_random(); | |
i += 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment