Skip to content

Instantly share code, notes, and snippets.

@santhalakshminarayana
Created September 15, 2019 18:18
Show Gist options
  • Save santhalakshminarayana/dbb743ad487711e0e2ffe8cd2d0f6d90 to your computer and use it in GitHub Desktop.
Save santhalakshminarayana/dbb743ad487711e0e2ffe8cd2d0f6d90 to your computer and use it in GitHub Desktop.
The area of a circle is defined as πr^2. Estimate π to 3 decimal places using a Monte Carlo method.
import numpy as np
def dst_to_origin(x,y):
return np.sqrt(x*x + y*y)
def monte_carlo_pi():
'''
sq_area=(2*r)**2
cir_area=pi*(r**2)
pi*(r**2) No.of Points inside Circle (2*r)**2
---------- == -------------------------- => pi = --------
(2*r)**2 No.of Points inside Square (r**2)
4 * No.of Points inside circle
==> pi = ------------------------------
Total no.of Points
'''
x=np.random.rand(100000)
y=np.random.rand(100000)
circle=0
for i,j in zip(x,y):
if dst_to_origin(i,j) <=1 :
circle+=1
return (circle/100000)*4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment