Skip to content

Instantly share code, notes, and snippets.

@Gerjo
Created December 14, 2014 15:44
Show Gist options
  • Save Gerjo/a228e6617a0d928b8d9f to your computer and use it in GitHub Desktop.
Save Gerjo/a228e6617a0d928b8d9f to your computer and use it in GitHub Desktop.
Monte carlo integration
console.clear();
function f(x) {
return 3 + Math.pow(x, 2);
}
var w = 2;
var h = 4;
var domain = w * h;
var n = 5000;
var under = 0;
for(var i = 0; i < n; ++i) {
var x = Math.random() * 2 -1;
var y = Math.random() * h;
if(f(x) > y) {
++under;
}
}
console.log("Darts approach: " + domain*(under/n));
var sum = 0;
for(var i = 0; i < n; ++i) {
var x = Math.random() * 2 -1;
var y = f(x);
sum += y;
}
console.log("Sum approach: " + w * (sum/n));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment