Skip to content

Instantly share code, notes, and snippets.

@peterc
Created February 23, 2013 13:44
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save peterc/5019804 to your computer and use it in GitHub Desktop.
Save peterc/5019804 to your computer and use it in GitHub Desktop.
Calculating pi using the Monte Carlo method in JavaScript
var r = 5;
var points_total = 0;
var points_inside = 0;
while (1) {
points_total++;
var x = Math.random() * r * 2 - r;
var y = Math.random() * r * 2 - r;
if (Math.pow(x, 2) + Math.pow(y, 2) < Math.pow(r, 2))
points_inside++;
if (points_total % 10000 == 0)
console.log(points_inside + "/" + points_total + " pi == " + (4 * points_inside / points_total));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment