Uploaded by kogamo5338

Computing PI using random numbers

advertisement
Discovering the PI using pyhton
In [1]: import random
import math
Let's understand what we are trying to do here
How can we determine the area of a circle?
Let's start of by doing something simpler - the area of a quarter-circle.
The area of a quarter circle can be done by calculating an enormous amount of points in a square and
getting the ratio. The ratio is the area of a quarter-circle in a square with side 1. Try to see this in the first
quarter of the cartesian graph
Ratio of quarter-circle = Total points inside the quarter-circle / Total points
1. You generate a random x and y, both within the range [0, 1]
2. The points inside the quarter circle are the points where the euclidean distance is less or equal than
1.
3. Calculate the ratio
Important:
The ratio of the quarter-circle to the small square is the same as the circle to the big square.
The small square goes from x, y
e[0, 1]
and the big square goes from x, y
The quarter-circle/circle is always inscribed in the small/big square
Ratio of a circle = Area circle / Area big square
Inside points / Total points = Area circle / 2r * 2r
4 * r^2 * Inside Points / Total Points = Area circle
See any resemblance? 4 * Inside points / Total points is the PI!
In [2]: total_points = 1000000
num_inside = 0
for i in range(total_points):
x = random.uniform(0, 1)
y = random.uniform(0, 1)
distance = math.sqrt(x**2 + y**2)
if (distance <= 1):
num_inside += 1
print(4 * num_inside / total_points)
3.141284
In [ ]:
e[−1, 1]
.
Download