Skip to content

Instantly share code, notes, and snippets.

@hagino3000
Last active April 13, 2016 10:47
Show Gist options
  • Save hagino3000/4411651 to your computer and use it in GitHub Desktop.
Save hagino3000/4411651 to your computer and use it in GitHub Desktop.
Check box-muller transform
clear;
alpha = rand(1, 1000);
beta = rand(1, 1000);
val1 = sqrt(-2 * log(alpha)) .* sin(2 * pi * beta);
val2 = sqrt(-2 * log(alpha)) .* cos(2 * pi * beta);
hist([val1,val2], 20);
"use strict";
function gaussianRandom(mean, std) {
if (mean === undefined || std === undefined) {
throw "Gaussian random needs 2 arguments (mean, standard deviation)";
}
return randByCentralLimitTheorem() * std + mean;
}
// 中心極限定理を使って標準正規分布N(0,1)を得る
function randByCentralLimitTheorem() {
var v = 0;
for (var i = 0; i < 12; i++) {
v += Math.random();
}
return v - 6;
}
// Module export
module.exports = gaussianRandom;
"use strict";
function gaussianRandom(mean, std) {
if (mean === undefined || std === undefined) {
throw "Gaussian random needs 2 arguments (mean, standard deviation)";
}
return randByBoxMullerTransform() * std + mean;
}
// Box Muller法を使って標準正規分布N(0,1)を得る
var randByBoxMullerTransform = (function() {
var vals = [];
function calc() {
var alpha = Math.random(),
beta = Math.random();
return [
Math.sqrt(-2 * Math.log(alpha)) * Math.sin(2 * Math.PI * beta),
Math.sqrt(-2 * Math.log(alpha)) * Math.cos(2 * Math.PI * beta)
];
}
return function() {
vals = vals.length == 0 ? calc() : vals;
return vals.pop();
}
})();
// Module export
module.exports = gaussianRandom;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment