Skip to content

Instantly share code, notes, and snippets.

@nils-werner
Created March 29, 2015 21:36
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 nils-werner/8e0b01b7d6833f852e2a to your computer and use it in GitHub Desktop.
Save nils-werner/8e0b01b7d6833f852e2a to your computer and use it in GitHub Desktop.
Calculating PI using NumPy and the montecarlo method
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