Skip to content

Instantly share code, notes, and snippets.

@mblondel
Created July 25, 2010 02:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mblondel/489233 to your computer and use it in GitHub Desktop.
Save mblondel/489233 to your computer and use it in GitHub Desktop.
Compute pi by MCMC
from random import random
"""
Find pi by the Monte-Carlo method.
area of a circle = pi r^2
area of a square = (2r)^2 = 4 r^2
Perform random uniform sampling between -1 and 1.
The proportion of points in the unit circle is:
p = (pi r^2) / (4r^2)
So pi = 4.0 * p
"""
N = 1000000
n_circle = 0
n_total = 0
for i in xrange(N):
x = random() * 2 - 1
y = random() * 2 - 1
# equation of the unit circle
if x ** 2 + y ** 2 < 1:
n_circle += 1
n_total += 1
print "pi = ", 4.0 * n_circle / n_total
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment