【问题标题】:How can I optimize this in order to make it run in less time?我该如何优化它以使其在更短的时间内运行?
【发布时间】:2019-10-13 09:45:35
【问题描述】:

我编写了一个程序,该程序接受一个 N 值并生成 N 个点,其随机坐标介于 0 和 1 之间。如果这些点包含在以 0 为中心的半径为 1 的圆中,则这些点与红色相关联, 0,否则为蓝色。目标是输出包含所有点的示意图,并从中计算出 pi 的近似值。

我想让程序运行得更快,因为N值越高,它的精度越高,但运行时间越长。 例如我想运行 N=10 000 000

----------------main.py
#def
import matplotlib.pyplot as plt
from prototypes import point

r=0

#input
N=int(input("Nombre de tirages?"))

#compute
for N in range (1,N+1,1):
    [x,y]=point()
    if x**2 + y**2 > 1:
        plt.scatter(x,y, s=1, c='b')
    else:
        plt.scatter(x,y, s=1, c='r')
        r=r+1

p=((5/2)*N)/r

#output
plt.axis([0,1,0,1])
plt.title('Pour N={N}, une valeur approchée de Pi est {p}'.format(N=N,p=p))
plt.show()
----------------prototypes.py
import matplotlib.pyplot as plt
import random

#create a random point
def point():
    x=random.random()
    y=random.random()
    return [x,y]

【问题讨论】:

  • 我会尝试在 for 循环中收集列表中的所有点,而不是直接绘制它们!最后,只用收集的点列表调用 scatter 一次。
  • 首先感谢您的回复。我对 python 和这个论坛很陌生,你能告诉我我可以实现这个的方式吗?
  • 小事很重要:为什么要在这里声明一次性清单? [x,y]=point() - 您可以改用 x,y = point()。大约有 10k 个列表根本不需要构建

标签: python performance math optimization


【解决方案1】:

当然,这就是我的意思(为了简单起见,我将所有内容放在一个文件中):

import matplotlib.pyplot as plt
import random

#create a random point
def point():
    x=random.random()
    y=random.random()
    return x,y # no need for a list, lists needs extra memory space to maintain their structure, while you just need two numbers

r=0

#input
N=int(input("Nombre de tirages?"))

#compute
points_red = [] # This list will collect the red points
points_blue = [] # This list will collect the blue points
for N in range (1,N+1,1):
    x,y=point()
    if x**2 + y**2 > 1:
        points_blue.append((x,y)) # Add the point to list as a tuple (x,y)
    else:
        points_red.append((x,y)) # Add the point to list as a tuple (x,y)
        r=r+1

p=((5/2)*N)/r

#output
# The scatterplot is a slow and heavy operation: we just do it once plotting all the points collected in the two lists before at the same time
plt.scatter([p[0] for p in points_blue], [p[1] for p in points_blue], s=1, c='b')
plt.scatter([p[0] for p in points_red], [p[1] for p in points_red], s=1, c='r')
plt.axis([0,1,0,1])
plt.title('Pour N={N}, une valeur approchée de Pi est {p}'.format(N=N,p=p))
plt.show()

【讨论】:

  • 非常感谢!关于列表以及它们的行为方式,我还有很多东西要学习!此外,您刚刚向我展示了如何正确使用分散功能,我很感激。
猜你喜欢
  • 2015-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-11
  • 1970-01-01
  • 2020-01-13
  • 2018-11-06
  • 2021-11-11
相关资源
最近更新 更多