Skip to content

Instantly share code, notes, and snippets.

@peterc
Created February 23, 2013 13:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterc/5019760 to your computer and use it in GitHub Desktop.
Save peterc/5019760 to your computer and use it in GitHub Desktop.
Calculating pi using the Monte Carlo method
r = 5
points_total = 0
points_inside = 0
loop do
points_total += 1
x, y = rand * r * 2 - r, rand * r * 2 - r
points_inside += 1 if (x ** 2 + y ** 2) < (r ** 2)
puts "#{points_inside}/#{points_total}: pi == #{4 * points_inside / points_total.to_f}" if points_total % 10000 == 0
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment