Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- We need to estimate the value of pi.
- 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
- 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
- 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)
- We know the equation of circle at origin of radius 1 is: x^2 + y^2 = 1^2=1
- 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.
- so,if we find 10000 points and find that how many is in cirle and how many is in square ie. pi/4
- so,multiple the above value with 4 and return the value of pi.
- '''
- import random
- import time
- INTERVAL = 10000
- circle_points = 0
- square_points = 0
- # Similar to srand(time(NULL))
- random.seed(time.time())
- for _ in range(INTERVAL * INTERVAL):
- # Random x and y between 0 and 1
- rand_x = random.randint(0, INTERVAL) / INTERVAL
- rand_y = random.randint(0, INTERVAL) / INTERVAL
- # Distance from origin
- origin_dist = rand_x * rand_x + rand_y * rand_y
- # Check if point lies inside unit circle
- if origin_dist <= 1:
- circle_points += 1
- square_points += 1
- # Estimate pi
- pi = (4 * circle_points) / square_points
- print(f"Final Estimation of Pi = {pi}")
Advertisement
Add Comment
Please, Sign In to add comment