Created
December 14, 2014 15:44
-
-
Save Gerjo/a228e6617a0d928b8d9f to your computer and use it in GitHub Desktop.
Monte carlo integration
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
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