我正在尝试创建一种经典的近似Pi的方法,该方法是将飞镖随机“扔”在带有内切圆的正方形内,然后计算落在圆上的飞镖与抛出的飞镖的比例
我的代码有效,但是我想增加被抛出的“飞镖”的数量。问题是我的代码运行非常慢。为什么会这样,我如何加快速度?
请参阅下面的代码。
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')
for i in range(darts):
x = np.random.uniform(-r,r)
y = np.random.uniform(-r,r)
dist = x * x + y * y
if dist <= r * r:
inCircle += 1
plt.scatter(x,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))
感谢您的帮助。
答案 0 :(得分:1)
代码的大部分时间都花在运行for循环上,因此您应该将注意力集中在那里。可以将Numpy.random.uniform设置为返回给定大小的随机数数组。通过分配2个数组类型以分别容纳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))
答案 1 :(得分:0)
我在这里看到2名嫌疑犯:
plt.scatter(x,y, marker='o', s=2, color = '#1f77b4')
-每个数字的速度可能会变慢plt.savefig(f'PiApproximationwith{darts}darts.png', dpi = 600); plt.show()
渲染图。 (更多点数=更多时间)尝试禁用第2点的线条,并使用1Milion飞镖运行。如果运行很短,您将知道其显示/渲染