Created
March 29, 2015 21:36
-
-
Save nils-werner/8e0b01b7d6833f852e2a to your computer and use it in GitHub Desktop.
Calculating PI using NumPy and the montecarlo method
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
from __future__ import division | |
import numpy | |
n = 1000000 | |
# 2D data spread uniformly across a square of A=1 | |
data = numpy.random.uniform(-0.5, 0.5, size=(n, 2)) | |
# Count points that are within distance 0.5 from center | |
inside = len( | |
numpy.argwhere( | |
numpy.linalg.norm(data, axis=1) < 0.5 | |
) | |
) | |
# Calculate pi | |
print(inside / n * 4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment