代码的大部分时间都花在运行for循环上,因此您应该将注意力集中在该循环上。Numpy.random.制服可以设置为返回给定大小随机数的数组。通过分配两个数组类型来容纳每个2000个变量,可以一次获得所有点。运行for循环查看圆中有多少个数组,然后将这两个数组同时传递到散点图,如下所示:
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np
from decimal import Decimal
darts = 2000 # number of "darts" to be thrown
r = 10 # radius/sidelength
plt.cla()
# Make a box with an inscribed circle
box = patches.Rectangle((-r, -r), 2 * r, 2 * r,
linewidth=2, edgecolor='k', facecolor='none')
circle = patches.Circle((0, 0), radius=r,
linewidth=2, edgecolor='k', facecolor='none')
inCircle = 0 # number of points that land in the circle
# Plotting
ax = plt.gca()
ax.add_patch(box)
ax.add_patch(circle)
ax.axis('equal')
plt.axis('off')
array_of_rand_x = np.random.uniform(-r, r, 2000)
array_of_rand_y = np.random.uniform(-r, r, 2000)
for i in range(darts):
x = array_of_rand_x[i]
y = array_of_rand_y[i]
dist = x * x + y * y
if dist <= r * r:
inCircle += 1
plt.scatter(array_of_rand_x, array_of_rand_y, marker='o', s=2, color='#1f77b4')
plt.title(f'Pi Approximation with {darts} "Darts"')
plt.tight_layout()
plt.savefig(f'PiApproximationwith{darts}darts.png', dpi=600)
plt.show()
# Computes pi
print(Decimal(4 * inCircle / darts))