Skip to content

Instantly share code, notes, and snippets.

@fiurthorn
Last active February 16, 2022 06:10
Show Gist options
  • Save fiurthorn/9c516e866546643d52126c9a958ea653 to your computer and use it in GitHub Desktop.
Save fiurthorn/9c516e866546643d52126c9a958ea653 to your computer and use it in GitHub Desktop.
Normal Distribution in javascript
/**
* https://en.wikipedia.org/wiki/Marsaglia_polar_method
*
* @param {*} mean Mittel
* @param {*} sd Spreitzung
*/
export function NormalDistribution(mean, sd) {
this._cache = [];
this.mean = mean;
this.sd = sd;
}
NormalDistribution.prototype._fill = function () {
let u, v, q, p
do {
u = 2.0 * Math.random() - 1;
v = 2.0 * Math.random() - 1;
q = u * u + v * v;
} while (q >= 1.0 || q == 0.0);
p = Math.sqrt(-2 * Math.log(q) / q);
let x1 = u * p;
let x2 = v * p;
this._cache.push(x1, x2);
};
NormalDistribution.prototype.next = function () {
if (this._cache.length === 0) {
this._fill();
}
var z = this._cache.pop();
return (z * this.sd) + this.mean;
};
/**
* @param {*} mean Mittel
* @param {*} sd Spreitzung
*/
export function EvenlyDistribution(mean, sd) {
this.diff = 2 * sd;
this.shift = mean - sd;
}
EvenlyDistribution.prototype.next = function () {
return Math.random() * this.diff + this.shift
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment