It is a story that I tried to estimate the pi stochastically (strictly speaking, Monte Carlo method) using Python's standard library random. (Expected reading time: 4 minutes)
Imagine the xy coordinates.
Draw a circle with radius r (let's call it C) centered on the origin O and a square with a side of 2r (let's call it S).
Randomly keep hitting dots in S.
When you hit enough points to fill the inside of S, you can say "the number of points in S: the number of points in C ≒ the area of S: the area of C".
If the number of points in S is "s_dot_num" and the number of points in C is "c_dot_num",
(c_dot_num) / (s_dot_num) = Area of C / Area of S = (π * r squared) / (2r) squared = π / 4
Because it becomes
π = 4 * (c_dot_num) / (s_dot_num)
I was able to define. After that, if you can find c_dot_num and s_dot_num respectively, you can estimate the value of π. (The value of r doesn't seem to matter)
This time I wrote it in Python.
estimate_pi.py
#Dots are randomly placed in a square with a side length of 1 to estimate the pi.
import random
def estimate_pi(n):
c_dot_num = 0
s_dot_num = 0
for _ in range(n):
x = random.uniform(0, 1)
y = random.uniform(0, 1)
distance = x**2 + y**2
if distance <= 1:
c_dot_num += 1
s_dot_num += 1
pi = 4 * c_dot_num / s_dot_num
return pi
if __name__ == '__main__':
print('When there are 100 dots, the pi is{}'.format(estimate_pi(100)))
print('When there are 1000 dots, the pi is{}'.format(estimate_pi(1000)))
print('When there are 10000 dots, the pi is{}'.format(estimate_pi(10000)))
print('When there are 100000 dots, the pi is{}'.format(estimate_pi(100000)))
※image
First time Second time Third time
It is about 3.141. As the number of trials n (= the number of times to hit the dot) is increased, the accuracy increases.
This time, I tried to estimate the pi using random numbers. Academically, the method of estimating some value using random numbers is called the "Monte Carlo method".
The code itself is not difficult at all, but when I first learned about it, I was excited to say, "Is there such an approach!", So as a memorandum.
Recommended Posts