Skip to content

Instantly share code, notes, and snippets.

@Irene-123
Last active January 20, 2021 07:33
Show Gist options
  • Save Irene-123/2d7d83e626737a06c4cb71349c5d6aad to your computer and use it in GitHub Desktop.
Save Irene-123/2d7d83e626737a06c4cb71349c5d6aad to your computer and use it in GitHub Desktop.
Monte Carlo Estimation of Pi in python
PROBLEM STATEMENT- You have a cicle of radius 1 embedded in the square . There are some random points everywhere ,some inside the circle
and some outside which contribute to the points in square
**************DISPLAY IS PROVIDED BELOW IN THE COMMENT SECTION********
ALGORITHM- 1. Generate some random numbers between 0 and 1
2. check the distance of the point from the origin
3. if x**2 + y**2 =distance <1 then the point lies inside the circle
4. Increment nums_points_circle
5. Increment nums_total_points .
Now , the question arises how to calculate the value of pi ?
area of circle /area of square = nums of points inside the circle /total points
πr<sup>2</sup> / (2.r)<sup>2</sup> = """
that is ,
π/4=nums of points inside the circle /total points
π= 4 * nums of points inside the circle /total points
Here, is the code below.
```python3
import random
def estimate_pi(n):
num_points_circle=0
num_points_total=0
for _ in range (n):
x=random.uniform(0,1)
y=random.uniform(0,1)
if x**2 + y**2<=1:
num_points_circle+=1
num_points_total+=1
return (4* num_points_circle)/ num_points_total
if __name__== "__main__" :
n=int(input())
result=estimate_pi(n)
print(result)
```
@Irene-123
Copy link
Author

IMG_1469

@Irene-123
Copy link
Author

This is an all-time favourite interview question .If its useful to you ,please star this gist ! Let me know if there are any improvements or suggestions ,will be appreciated !!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment