Как я могу оптимизировать это, чтобы заставить его работать за меньшее время? - PullRequest
0 голосов
/ 13 октября 2019

Я написал программу, которая принимает в аргументе значение N и генерирует N точек со случайными координатами от 0 до 1. Затем эти точки ассоциируются с красным цветом, если они включены в круг радиусов 1 с центром в 0,0 и синий цвет в противном случае. Цель состоит в том, чтобы вывести схему, включающую все точки, и вычислить из них приблизительное значение числа пи.

Я бы хотел, чтобы программа работала быстрее, поскольку чем выше значение 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]

1 Ответ

1 голос
/ 13 октября 2019

Конечно, вот что я имею в виду (для простоты я собрал все в один файл):

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()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...