Question
Given Python's random() function that returns a random value between 0 and 1.
Approximate π using this function.
Hello everyone! I've got an intriguing question for you today. With Python's random function that generates values between 0 and 1, can you estimate the value of π? It might seem challenging initially, but there's a clever and fascinating method to achieve it. If you're up for the challenge, put this article on hold and dive right in!
Let's get started!
Step-by-Step Solution
For the solution, let's look at this circle with a radius of 1 and the surrounding square with a side length of 2.
More precisely, our focus is on the top right quadrant of this square. Inside this top right quadrant, we can place some random points using a random function. They will look like this, for example. So, I just used the random function to generate x and y coordinates between 0 and 1.
Now, we can mark those points with two colours. The yellow points are inside the circle, and the blue points are outside of the circle.
If we now mark those two areas, we can see an approximation that will give us an approximation of π. This approximation is given as follows:
First of all, the yellow area is a quarter of the whole circle, so we have the area as π times r squared divided by four, and because r is one in our case, we just have π divided by four. The green area, on the other hand, is just a square with a side length of one, so the area is 1.
Now, let's use our values and substitute them in the approximation above, which will give us the approximate value of π:
When we write a program to calculate this, we already have the number of all points, and the only question is, what is the number of yellow points?
So, how many yellow points are there? To get this number, we can use the following condition: the distance of the yellow points to the centre of the circle must be less than one. When this condition is met, the point is yellow and inside the circle. If the distance is greater than one, the point will be blue and outside of the circle.
Now, we have everything together to write our code.
One-Page Solution
Source Code
The source code is given below!
# Estimating Pi using Python
import random
def estimate_pi(n):
numPointCircle = 0
numPointTotal = 0
for i in range(n):
x = random.uniform(0, 1)
y = random.uniform(0, 1)
distance = x**2 + y**2
if distance <= 1:
numPointCircle += 1
numPointTotal += 1
return 4 * numPointCircle/numPointTotal
numOfPoints = int(input("Enter the number of points: "))
print(f"Pi estimate with number of points in the circle as {numOfPoints} = " + str(estimate_pi(numOfPoints)))
Give it a star 🌟
Comments in code? Nah, I prefer leaving cryptic messages for future archaeologists to decipher. 👻😂
Thanks for 7753!