If you just want to use pi
import math
print(math.py)
That's fine, but I'd like to see how I'm looking for 3.14. Therefore, I would like to find the pi with a stochastic model.
First, set a random number from 0 to 1 for each of the x and y coordinates and hit a point.
import random
x, y = random.random(), random.random()
If the number of squares of x and y and the sum of them is less than 1, the point is inside a circle with a radius of 1.
number = x ** 2 + y ** 2 #Inside the circle if this is within 1
Repeat this many times, and if the number of repetitions is the denominator and the number of times within 1 x 4 (assuming that the same result is obtained in all quadrants) is the numerator, the pi is calculated. Let's try it about 1000 times.
import random
incount = 0
def GenerateRandom():
x, y = random.random(), random.random()
number = x ** 2 + y ** 2
return number
iteration = 1000
for ite in range(iteration):
check = GenerateRandom()
if (check < 1):
incount += 1
quadrant = 4 #All quadrants
print(incount * quadrant / iteration)
3.2
Well, it's subtle. It seems that the number was small, so let's try it 10 million times.
#It takes about 5 seconds
3.141382
Is it good?
I wasn't really impressed when the numbers came out, so let's visualize it with matplotlib.
First 1000 times version
import random
import matplotlib.pyplot as plt
def GenerateRandom():
x, y = random.random(), random.random()
number = x ** 2 + y ** 2
return [number, x, y]
iteration = 1000
for ite in range(iteration):
check = GenerateRandom()
if (check[0] < 1):
plt.scatter(check[1], check[2], c = 'red', s = 10)
else:
plt.scatter(check[1], check[2], c='blue', s = 10)
plt.title('Monte Carlo Method')
plt.xlabel("x")
plt.ylabel("y")
plt.show()
Wait about 10 seconds ...
It's not easy to understand, so let's try the version 10 million times.
import random
import matplotlib.pyplot as plt
def GenerateRandom():
x, y = random.random(), random.random()
number = x ** 2 + y ** 2
return [number, x, y]
iteration = 10000000
for ite in range(iteration):
check = GenerateRandom()
if (check[0] < 1):
plt.scatter(check[1], check[2], c = 'red', s = 10)
else:
plt.scatter(check[1], check[2], c='blue', s = 10)
plt.title('Monte Carlo Method')
plt.xlabel("x")
plt.ylabel("y")
plt.show()
Once you've done this, take a walk away from your computer. By the time you come back, the process should be finished.
It is easier to understand if the graph is made square, but you can see that it is distributed in a beautiful arc.
Calculating this doesn't mean anything is born, but if you're interested, I'd appreciate it if you could give it a try.
Information Processing Society of Japan
Recommended Posts