Skip to content

Instantly share code, notes, and snippets.

@ryanseys
Created March 17, 2015 17:26
Show Gist options
  • Save ryanseys/c1c02cd889e925ea5d3e to your computer and use it in GitHub Desktop.
Save ryanseys/c1c02cd889e925ea5d3e to your computer and use it in GitHub Desktop.
// Acceptance rejection technique
function AcceptReject() {}
AcceptReject.prototype.inverseG = function(x) {
return -1 * Math.log((1 - x) / 2.85);
};
AcceptReject.prototype.f = function(x) {
return 20 * x * Math.pow(1 - x, 3);
};
AcceptReject.prototype.g = function(x) {
return 2.85 * Math.pow(Math.E, -x);
};
AcceptReject.prototype.genX = function(){
var u, x, v, gx, fx;
var iterations = 0;
do {
u = Math.random();
v = Math.random();
x = this.inverseG(u);
gx = this.g(x);
fx = this.f(x);
iterations++;
} while((1 * gx * v) > fx);
console.log('x: ' + x, 'interations: ' + iterations);
};
var runner = new AcceptReject();
for (var i = 0; i < 10; i++) {
runner.genX();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment