Suppose we already know that the formula for calculating the area of a circle is: πr², and the area of a square is r², but we do not know the specific value of π. The simulation results are as shown in the figure: We compare the area s1 of the 1/4 circle with the area s2 of the square to get 1/4π, so π is equal to 4 times s1/s2.
The maximum value of the horizontal and vertical coordinate axes in the figure is 1. The red arc is a 1/4 circle with the origin as the center and 1 as the radius. The simulation method is to randomly generate points (x, y), where x and y both belong to the (0, 1) interval. If the point falls within a 1/4 circle of radius 1, the area of the circle is counted, and the total number of points is counted as the square. area.
import random
import matplotlib.pyplot as plt
import numpy as np
def mock(n):
# 画个坐标轴
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1])
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
# 随机生成0,1的点
x = random.sample(range(1, n), n - 1)
y = random.sample(range(1, n), n - 1)
xx = [i / n for i in x]
yy = [i / n for i in y]
plt.scatter(xx, yy, color='g')
# 画一个1/4圆
x = np.linspace(0, 1, n)
y = pow(1 - x ** 2, 0.5)
plt.plot(x, y, color='r')
# 计数圆内的点模拟圆面积
count = 0
for (i, j) in zip(xx, yy):
d = pow(i * i + j * j, 0.5)
if d <= 1:
count += 1
# s1/s2*4
print(count / n * 4)
plt.show()
if __name__ == '__main__':
mock(1000)