Created
September 7, 2018 21:40
-
-
Save arose13/df1f9d9ed428f7acf686146762e8298d to your computer and use it in GitHub Desktop.
A (hopefully) extremely high precision Monte Carlo estimation of pi
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
| # 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