Skip to content

Instantly share code, notes, and snippets.

@arose13
Created September 7, 2018 21:40
Show Gist options
  • Select an option

  • Save arose13/df1f9d9ed428f7acf686146762e8298d to your computer and use it in GitHub Desktop.

Select an option

Save arose13/df1f9d9ed428f7acf686146762e8298d to your computer and use it in GitHub Desktop.
A (hopefully) extremely high precision Monte Carlo estimation of pi
# Extremely high precision monte carlo estimation of pi
import numpy as np
import numpy.linalg as la
from sympy import N, pi
def calculate_pi():
inside, n = 0, 1e6
for i in range(int(n)):
nth = i+1
point = np.random.uniform(-1, 1, size=2)
inside += 1 if la.norm(point, 2) <= 1 else 0
estimate = N(4*inside / nth, 1000)
print(
f'Pi: {estimate:.10f}, Precision: {(estimate/pi - 1).evalf():.5%}, N: {nth}, log(N): {np.log10(nth):.3f}',
end='\r' if nth < int(n) else '\n'
)
if __name__ == '__main__':
calculate_pi()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment