Exemple d'algorithme pour évaluer pi en utilisant la méthode de Monte Carlo:

from random import uniformimport numpy as npimport matplotlib.pyplot as pltRadius = 1.0Nb_Data = 10000x_list = []y_list = []test = []Nb_Data_In = 0for i in range(Nb_Data):x = uniform(-Radius,Radius)y = uniform(-Radius,Radius)x_list.append(x)y_list.append(y)if x**2+y**2 > Radius**2:test.append(0)else:test.append(1)Nb_Data_In = Nb_Data_In + 1pi = 4.0 * Nb_Data_In / Nb_Dataprint 'pi: ', picolor1=(0.69411766529083252, 0.3490196168422699, 0.15686275064945221, 1.0)color2=(0.65098041296005249, 0.80784314870834351, 0.89019608497619629, 1.0)colormap = np.array([color1,color2])plt.scatter(x_list,y_list,c=colormap[test])plt.savefig("MonteCarloPi.png")plt.show()
Recherches associées
| Liens | Site |
|---|---|
| Monte Carlo method | wikipedia |
| Estimating Pi using Monte Carlo Simulation | youtube |
| Calculating Pi (π) using Monte Carlo Simulation | youtube |
| Simple Monte Carlo Simulation to Calculate Value of Pi using Excel | youtube |
