import matplotlib.pyplot as plt
X = np.random.uniform(-1, 1, size = (500,2))
x = X[:,0]
y = X[:,1]
masks = np.sqrt(x**2 + y**2) < 1
pi_est = 4 * sum(masks)/len(x)
fig, ax = plt.subplots()
# 在坐标系中添加一个单位圆。
ax.add_patch(circ)
#将落在单位圆内的点用蓝色“x”标记,落在单位圆外的点用红色“.”标记。设置坐标轴比例相等,并添加标题显示估计的π值。
plt.scatter(x[masks], y[masks], marker=“x”, alpha=0.5, color = ‘b’)
# plot data outside the circle
plt.scatter(x[~masks], y[~masks], marker=“.”, alpha=0.5, color = ‘r’)
plt.axis(‘scaled’)
plt.title(‘Estimated $pi$ = %1.3f’ %(pi_est))
plt.xlim(-1, 1)
plt.ylim(-1, 1)
# define a function of estimating pi
def est_pi(n):
X = np.random.uniform(-1, 1, size = (int(n),2))
x = X[:,0]
y = X[:,1]
masks = np.sqrt(x**2 + y**2) < 1
pi_est = 4 * sum(masks)/len(x)
return pi_est
# 创建一个数组n_array,包含从1000到100000的100个点数。创建一个空数组est_pi_array,用于存储对应的π估计值。
est_pi_array = np.empty(len(n_array))
# 遍历n_array中的每个点数,调用est_pi函数估计π的值,并将结果存储在est_pi_array中。
i = 0
for n in n_array:
pi_est = est_pi(n)
est_pi_array[i] = pi_est
i = i + 1
fig, ax = plt.subplots()
plt.semilogx(n_array, est_pi_array)
plt.xlabel(“Number of random number”)
plt.ylabel(“Estimated $pi$”)
plt.axhline(np.pi, color=“r”);
plt.grid(True, which=“both”, ls=“–“)
plt.show()