imashutosh51

Estimating the value of Pi using Monte Carlo

Nov 7th, 2022 (edited)
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.35 KB | None | 0 0
  1. '''
  2. We need to estimate the value of pi.
  3. Area of cirle of radius r is : pi*r^2     ie. -1 to 1 on the x axis and -1 to 1 on y axis
  4. Area of square of the same size : (2*r)^2=4r^2  ie. -1 to 1 on x-axis and -1 to 1 on y axis
  5. so,(Area of cirle of radius r /Area of square of same size) == (pi/4)  == (number of points in circle/number of points in square)
  6. We know the equation of circle at origin of radius 1 is: x^2 + y^2 = 1^2=1
  7. so if our -1<=x<=1 && -1<=y<=1 then that point will definitely come inside the square but can go outside the circle also.
  8. so,if we find 10000 points and find that how many is in cirle and how many is in square ie. pi/4
  9. so,multiple the above value with 4 and return the value of pi.
  10. '''
  11. import random
  12. import time
  13.  
  14. INTERVAL = 10000
  15.  
  16. circle_points = 0
  17. square_points = 0
  18.  
  19. # Similar to srand(time(NULL))
  20. random.seed(time.time())
  21.  
  22. for _ in range(INTERVAL * INTERVAL):
  23.  
  24.     # Random x and y between 0 and 1
  25.     rand_x = random.randint(0, INTERVAL) / INTERVAL
  26.     rand_y = random.randint(0, INTERVAL) / INTERVAL
  27.  
  28.     # Distance from origin
  29.     origin_dist = rand_x * rand_x + rand_y * rand_y
  30.  
  31.     # Check if point lies inside unit circle
  32.     if origin_dist <= 1:
  33.         circle_points += 1
  34.  
  35.     square_points += 1
  36.  
  37.     # Estimate pi
  38.     pi = (4 * circle_points) / square_points
  39.  
  40. print(f"Final Estimation of Pi = {pi}")
Advertisement
Add Comment
Please, Sign In to add comment