Last active
August 29, 2015 14:09
-
-
Save SuborbitalPigeon/b137af9aa28d8491d6b3 to your computer and use it in GitHub Desktop.
Estimates pi using a Monte-Carlo method
This file contains 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
import numpy as np | |
import numpy.random as random | |
iters = 10e6 | |
# 1. The equation of the area of a unit circle is `ac = pi * 1^2 = pi' | |
# 2. The area of a 2x2 square is `as = 2^2 = 4' | |
# 3. The probability of a random point being in the circle is pi / 4 | |
# 4. Given a random point, the point is in the circle if the point's | |
# radius from the centre is less or equal to 1 | |
# 5. If the proportion of points inside the circle is multiplied by 4, | |
# this value will be an approximation of pi | |
# Random values between -1 and 1 | |
x = 2 * random.random(iters) - 1 | |
y = 2 * random.random(iters) - 1 | |
r = np.sqrt(x**2 + y**2) | |
# Number of points inside the circle | |
inside = (r <= 1).sum() | |
pi = 4 * (inside / iters) | |
print("Pi=", pi) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment